Software Engineer/Economist

A picture of Paul S. Tuon

Paul S. Tuon

`~The engine of your inginuity is limited only to your imagination!!!~`


UX Engineer

Minneapolis, MN (US)

Attended: University of

Minnesota (Twin Cities)

Majored: Economics/Computer

Science

A picture of Paul S. Tuon in a graduation gown


Expertise

Programming:

I am a Software Engineer/Economist-- specializing in all kinds of software applications development.

My field of expertise:

Java, Delphi, C#, Python, PHP, Node.js, JavaScript, jQuery, Ajax, MySQL, PDO, and of course, CSS.

I enjoy programming and it feels like a hobby to me.

It probably falls in both categories of programming and hobbies!!!


Hobbies

Social media:

Love going online and interacting with total strangers on social medias!

It's fun!!

And it's so 21st century and beyond!!!

Hardly a bane on my existence!

Sports:

Enjoy watching/playing soccer, Karate, and the World Cup.

And I was a long time avid season-ticket holder of the Minnesota United Prefessional Soccer Team prior to Covid-19.


A Lifelong Dream

Going as far back as I could remember (even being just a child), I have always dreamed of owning my own company and taking it to the public.

It is a lifelong dream that is still with me today!

Hey, I can dream, too!

Can't I?

I can say this:

My will, determination, and resolve are unshaken!!!

Never have been and never will be!!!


Photos

www.ZeroNilZilch.COM              Where the future is already here!                            Explore, see the horizon,       open your mind and let your curiosity run wild,       discover, inspire and enrich your learning!!!              The engine of your inginuity is limited only to your imagination!!!              Welcome to the 21st century and beyond where digital mobile rules!                            This website and all of our affiliate sites are mobile-friendly!                            This means that you can use your mobile phones or any portable small device to surf and shop with us conveniently and securely at all of our affiliate sites!!!                            They're built for the Millenials, where all things Millenial, the Millenials' way!!                            Go ahead and fire up your smartphones and load this website and see if it's mobile-friendly or not!

search .....


Here is how to get started trading options for beginners

If you've never heard or knew what an option is, you've come to the right place. Take a look at my other tutorial called "introduction to options" and start from there. Once you get a good grasp of the concept, look around and pick a brokerage service and signup an account.

There are lots of brokerage services out there that want your business and pick a discount brokerage service because it's cheaper. Brokerage services like Fidelity Investments, Ally Financial, Options House (was bought by E-Trade in 2016, so go to E-Trade.com), Charles Schwap, Scottrade, TD Ameritrade, Tradestation, Tastyworks, etc., or just Google around using the term "low commissions options brokers."

Make sure to read their pricing policy because some brokers charge low fees but require you to have a certain minimum amount in your account. Ally Financial, TD Ameritrade (I think) and Scottrade (I think) have no minimum. Tastyworks has a very unique pricing model--especially if you're an active trader--that they only charge you when you place an opening position trades but they don't charge you when you close your positions.

Remember that all other brokerage services charge you when you open your trade and also charge you when you close out your position. That's $10 for just one round trip--a $5 for opening position and a $5 for closing position. That's a lot of $5(s) and $10(s) to waste.

Please check the following out:

tastyworks.com

Another very good brokerage house that has zero commissions, zero options contract fees, zero deposit minimum. Please check the following out:

Webull.COM There are plenty of other brokerage services that have no minimum--or if they do, it is very little minimum and the majority of them have a minimum of $25. Some brokers have no minimum but require their clients to keep accounts active by mean of trading. So look around.

FYI: Check out the following website for online discount brokerage services comparisons. Scroll down to the bottom of that page for more comparisons: TD Ameritrade vs Ally Invest Review. Once you identified which brokerage service is right for you, go ahead and signup an account with them. They will ask for your social security # (or government-issued id # for foreign applicants), networth, and trading experience. The latter two you don't have to tell them the exact truth. For networth put something meaningful like over $100,000 even though you only have a few thousand dollars to trade.

A Side Note: Welcome to the 21st century and beyond, world! You are now can participate in options no matter where you are in the corner of the world, as long as you have internet connection, a government-issued id # (for foreign), and most importantly, money, and you can signup an account with one of the many online brokerages and trade stocks, options, bonds, etfs, and many other investment instruments at the tip of your fingers. This is the modern day Silk Road.

Networth is what you're worth at the present time and that includes your house, stock/bond holdings, savings, IRAs/401k, and other valuable assets that you can quantify. Also, in the application, it will ask how much of your current networth is liquid--meaning usable cash or can be easily turned into cash in a moment of notice. Again, you don't have to tell them the truth. Just put something like $20,000 or $30,000.

Notice that if you have IRAs/401k they are considered as liquid assets because you can withdraw or borrow from your accounts. Other notable liquid assets are bank accounts (checking/savings/preferred), CDs, money market accounts, stocks, tradable bonds, notes, account receivables, etc.

As for experience, one of the questions in the new-account application will ask is, how many years you have been trading and how many trades you have made or expect to make per year? Put something like intermediate (or a few years) because you have me as your mentor and that counts as experience (in my mind).

Most brokerage services establish a minimum experience criterio in which the number of years multiplied by the number of trades must be greater than 100. Most brokerage services consider this minimum experience criterio "liberally" that includes both real trades and simulated practice trades. Yes, you heard it right: your practice sessions count as experience and it makes a lot of sense.

So if you're not sure if you should go ahead and open a real trading account, you should consider applying for a paper trading account and see for yourself if it's what you're looking for. This way, once you are comfortable of what you're doing, you can apply for a real trading account.

Just inquire about them! They will be eager to help you because once you know how to trade options, they'll know that you'll most likely open a real trading account with them and giving them your business.

Let me tell you this: trading options is a lot easier than it sounds. Trading options is very simple--simple enough that even if you never knew what an option was [before reading my articles on options and] can start trading options in a very short amount of time.

Most brokerage services have a great paper trading simulator to get you comfortable if you specifically inquire about them for the purpose of paper trading before applying for a real trading account. Investopedia has a very good trading simulator for free for anyone that signup a free account for just the purpose of learning how to trade. Check this out:
Investopedia Free Account Signup After you've signed up, login to your free account and begin your trading simulator. Investopedia calls this trading simulator a "game" because it's like a game you play for "fun." You can select a variety of trading games, such as trading games for beginners (meaning beginner options traders) by selecting and putting a checkmark on "Beginners" options and click on "Join Selected Games" to go to the trading simulator page. On that page on the left side sidebar, you can find trading simulators: simulate trading of stocks, options, futures, and other trading games. There is a well-documented "how-to" guide to help you get started as well.

In addition, you may want to signup for a free account at Yahoo Finance where you can get access to all kinds of investing information. Once you have a free account, you can create as many portfolios as you want, say, one portfolio contains certain stocks or a group of industry stocks, and another contains certain investing tastes, such as income verses growth stocks.

Another very good website is called investing.com where you can signup for a free account and get access to all kinds of investing information, such as charts, technical and fundamental analysis, stocks screener, news alert on stocks, stock watch, etc.

Also, another very good website is called finviz.com where you can signup for a free account and get access to all kinds of investing information, particularly charts. Technical chart analysis in particular is very powerful and a must read if you are swing trading, looking to make quick profits using stock channels where stocks often move in a range bound, say, stocks that move between the resistance and support levels more frequently.

For those of you who are eager to apply for a real trading acccount, just put some experience, say, a few years and about 30 to 50 trades per year to get your account approved. You don't need experience for the types of trades you'll be doing. Hey, you have to start somewhere and right here is the best place for you to get started.

In the brokerage services application, it offers a variety of account types for you to choose. The following lists the account types you can open:

  • Individual (Individual, Joint, and Retirement Account). This is a regular account for individual single person, married joint account, or a retirement account such as for an investment club.

  • Individual (Trust and UGMA/UTMA). This is an account for a trust or for accounts setup for your minors for their retirement investment account.

  • IRA (Individual Retirement Account). This is an account setup for an IRA/401k retirement account.

  • Single Fund. This is an account setup as a managed fund such as an investment fund, a hedge fund or a mutual fund that has only one type of fund under management, e.g., a long term growth fund.

  • Multiple Funds. This is an account setup as a multiple managed fund such as an investment fund, a hedge fund or a mutual fund that has multiple types of fund under management, e.g., a value fund, an aggressive fund, a long term growth fund, a bond fund, an emerging fund, etc.

  • Financial Advisor. This is an account type for individuals or companies setup to offer and manage investment for their clients.

  • Institution (Partnership, Corporation, Limited Liability Corporation, and Unincorporated Business). This is an account type for institutions such as endowment, schools/churches/non-profit organizations retirement funds, individuals formed as a partnership, a corporation setup to manage their own investment and/or their clients' investment. Also, an account for an investment club can signup for institution account as well.

Most of you probably should apply for the first one: Individual (Individual, Joint, and Retirement Account). But if you have minors that you want to expose them to savings and investing, you might also want to signup the second account type: Individual (Trust and UGMA/UTMA).

If you have IRA/401k accounts at your employers or somewhere else, you might want to open an IRA account and transfer them to your accounts at the brokerage services so that you can manage your own investment. It is safer than you think using the trading methods described in this website: covered calls and covered puts.

Furthermore, IRA/401k accounts are allowed to use up to level 3 trading methods. This means that IRA/401k accounts can use long puts/calls, married puts, straddles, strangles, and credit spreads. That is a lot of strategies at your disposable.

All types of accounts, includling IRA accounts, allow you to trade options, in addition to invest in other types of investments, such as stocks, bonds, mutual funds, etfs, warrants, etc.

In options, there are at least three levels based on experience. For most of you, the first three levels are enough for now:

  • Level 1: Is for beginners who have no experience in options trading.

    Level 1 allows you to trade:
    • Covered calls. Covered calls sold against stocks held long in your brokerage account.
      • Buy-writes (simultaneously buying a stock and writing a covered call).

      • Covered call roll-ups/roll-downs.
    • Cash Secured Puts. Covered Puts sold against funds held in your brokerage account.

    This is for you beginners who had no idea what an option was before reading my tutorials. Well, even after reading my tutorials, consider yourself as a beginner and signup for level 1. In this level you are allowed to buy/sell stocks and trade two types of options: covered call and cash-secured put. For most of you, level 1 is enough for a while.

    Once you have demonstrated that you know how to trade covered calls and cash-secured puts and also show an increased in your account balance because of your trades were successful, and then you can apply for an upgrade to the next trading level, which is level 2.

    Again, in level 2, you have to demonstrate that you know how to trade vertical legs strategies before you are granted to the next level, which is level 3.

  • Level 2: Is for intermediate level or people who have some experience in options trading--for people who know how to trade vertical legs strategies.

    Level 2 includes all Level 1 strategies, plus:


  • Level 3: Intermediate to advanced strategies for people who know how to trade credit spreads and other multiple legs strategies. Check out the tutorials on options spreads: Option Spread Strategies. Level 3 includes all Levels 1 and 2 strategies, plus:

    • Equity debit spreads (commonly called debit spreads).

    • Equity credit spreads (commonly called credit spreads).

    • Equity calendar/diagonal spreads

    • Index debit spreads (commonly called debit spreads but using index instead of individual stocks).

    • Index credit spreads (commonly called credit spreads but using index instead of individual stocks).

    • Index calendar/diagonal spreads

  • Level 4: Advanced strategies for people who know how to trade credit spreads and other multiple legs strategies--options traders who have lots of experience in options trading.

  • Level 4 includes all Level 1, 2, and 3 strategies, plus:

    • Naked equity puts

  • Level 5: Advanced strategies for people who have lots of experience in options trading and trade millions and billions of dollars per year. Level 5 is very strict to qualify to get in and requires large sum of money to open an account. It is usually reserved for sophisticated professional and institutional traders. Levels higher than 3 is for specialized traders.

  • Level 5 includes all Level 1, 2, 3, and 4 strategies, plus:

    • Naked equity calls

  • Level 6: Advanced strategies for people who have lots of experience in options trading and trade millions and billions of dollars per year. Level 6 is very strict to qualify to get in and requires large sum of money to open an account. It is usually reserved for sophisticated professional and institutional traders. Levels higher than 3 is for specialized traders.

  • Level 6 includes all Level 1, 2, 3, 4, and 5 strategies, plus:

    • Naked index calls

    • Naked index puts

  • To apply for the upgrade steps, say level 2, 3, etc, you would contact your brokerage service and tell them you want to upgrade your account level. In most brokerage services, there is a button in your account dashboard that you can press to send your request and a notification of your approval/disapproval will be sent to you via email.

In the application, they might give you the option of applying for a margin account (as well) to go along with your regular trading account. A margin account is an extra priviledge account offered to most applicants who want leverage on their account -- and that is -- using brokerage money to control a huge position.

In essence, a margin account allows you more buying power (or trading power in this case) -- usually between 50% to 80% of your account balance. For example, if you have $2,000 in your trading account available for trade, your actual available trading money is between 50% to 80% of $2,000, which is about $3,000 (using a 50% margin account). The percentage is vary from applicant to applicant, depending on each applicant's creditworthyness.

You need to apply for a margin account during the initial application signup or at any time thereafter by contacting your brokerage service and requesting for a margin account. You'll get notified of their approval/disapproval in a short period of time. So if you want to have leverage to control more trading power and generate more profits, you can apply for a margin account to go along with your regular trading account.

A margin account is a loan account where the margin money is loaned to you to allow you to use that loaned money to trade stocks/options (in addition to your own money). But you have to pay interest on the loaned money. The interest rate is comparable to market interest rate like prime rates or rates people pay on their car loans or credit card payments.

Once you are approved of a margin account, your regular trading account should say that you're allowed a priviledge of a margin account; and if you have a balance in your regular trading account of, say, $10,000, it should show that your maximum funds available to trade is $15,000 (if you're approved of a 50% margin account).

So having a margin account is a huge advantage for most traders because you can use leverage to control huge position without spending your own money. That's why most experienced traders have margin account and they make use of their loaned money from their margin account to their advantage all the time to control huge position and therefore generate huge profits.

Once you are approved of a margin account and you're using your regular trading account to trade, your account should list two balance amounts: one for your regular trading account balance (for example, balance: $10,000) and another for the combined amount of your own money and the margin money (for example, available for trading balance: $15,000).

If you trade on your account, the margin interest kicks in and accrues either on a monthly basis or quarterly basis depending on your brokerage service's term of loan. So please read your margin account term of contract. Most brokerage services charge you on a monthly basis. So each month it automatically should show the accrued margin interest amount and that amount is deducted from your regular account balance. So you don't have to do anything on your part as long as you have enough balance to cover the accrued interest.

If you don't have enough money in your regular account balance, it will show a negative balance on it and the brokerage service will activate what is called a house call. A house call is a term used to indicate that you owed money to the brokerage service and it wants you to pay it for the next 30 days -- either depositing more money into your account or sell some of your holdings just enough to cover the house call balance. After 30 days from the house call notice and the balance is not paid, the brokerage service will try to collect the balance from you by selling your holdings just enough to cover their dued balance.

Also in the application, they might ask you how often do you trade? And how much per trading session? Again, you don't have to tell them the truth and putting something like two or three times a month or once a month.

In actuality, you will most likely trading monthly but who to dictate how often you trade? It's your money and you can trade once every five years if you want. As for how much, put something like $2000 to $5000 or whatever amount you wish and it won't effect your approval of the application. These questions only for them to help them learn about your aptitude and risk tolerance as an options trader.

Once you are approved, you can start the process of depositing funds into your account and start trading. I recommend starting out depositing into your account of at least $2000 and use the whole balance [or close to it] to buy a stock. That way, you can put every penny of your money to work for you instead of having some money sitting in your trading account doing nothing.

If you can afford to deposit more I think it is to your advantage, because the more money you put it to work for you the more stream of income you generate. The optimum firepower that I usually recommend to my friends and relatives is to start out about $5000 and put the whole $5000 to work right away and go from there. Of course, the more money that you can put it to work for you the more stream of income is coming to you.

The first trade you make should be a covered call. And repeat that trading process for awhile and see how your progress is. In other words, is your account balance higher than the original balance after a few trades?

If not, you might want to try to dump the stocks you have and move on to other stocks and start to do your homework on some other stocks and go from there.

If your account balance is higher, you have to decide if you want to continue on doing the same thing or move on to other strategies, such as the selling of cash-secured puts. Or you can do both if you have enough money for both. But make sure you start with covered call.

Meanwhile, as a beginner in options trading, you always want to learn more about options so that you can improve your skill levels and earn more profits. Here are some very good videos by Adam Khoo that teach you how to trade options as a beginner.
Professional Stock Trading Lesson For Beginners. Five Power Candlestick Patterns in Stock Trading Strategies Lesson For Beginners. Market Cycles in Stock Trading Strategies Lesson For Beginners. Trade Like a Casino for Consistent Profits For Beginners. Part I. Trade Like a Casino for Consistent Profits For Beginners. Part II. That is it!

Introduction to IPO

Article Date: August 9, 2014
By Paul S. Tuon

What is a stock?

The answer to that question may seem so obvious but it's not as a clear cut as a lot of you might think. So what exactly is a stock? Before I answer that, let's start from the basic principle of businesses. Enterprising business operations can be conducted in a number of different forms. The most notably common among the various possiobilities are the following:

  • Sole Proprietorships

  • Partnerships

  • Trusts and Estates

  • S Corporations

  • C Corporations
Among other forms of enterprising businesses that are part of the microeconomics are self-employment, freelance employment, syndicating employment, contracting employment, home-based enterprising business, internet-based enterprising businesses (buying and selling online, such as Noon2Noon.COM, Craigslist, EBay, Amazon, etc.)

Almost all enterprising businesses start out at the inception as a closely held, private business entity. There is rare (or virtually none) that an enterprising business starts out at its inception as a publicly traded company; the only exception is when a company is spin-off from its parent company and instantly becomes a publicly traded company.

The reason that no company starts out as a publicly traded company is that no investor would want to invest in an unknown company that just pops up from nowhere and sells shares to the public. Before the public sink their hard earned money into a company the public need to feel confidence in the company's going concern, and that company has to have a solid foundation and a good track record of performance and has a bright future.

When an enterprising business became a well-established enterprising business entity as a privately held business entity, then it might want to think about becoming a publicly traded company.

There is a variety of reasons why a privately held business entity might want to become a publicly traded company. There are pros and cons of being a privately held business entity. And also, there are pros and cons of being a publicly traded company.

There are no advantages of one form of entity over the other. It's just a matter of choice or situation--[really]. In some situations, it's better off to remain as a private business entity. In other situations, it's better off to become a publicly traded company. We won't go into great details on the pros and cons.

When a privately held business entity decides to become a publicly held company, the company is said to be going public. In other words, the owner(s) of the privately held business entity are selling part-ownership to the general public.

The keyword here is part-ownership -- and not the whole-ownership of the company -- because the original owner(s) of the closely held business entity are selling only part of the company and not the whole company. When you buy a part-ownership, often called a stock in a company, you become a part-owner (also known as shareholder). You immediately own a part (no matter how small) of every thing the company owns -- such as buildings, office equipments (such as furnitures, computers, copy machines, etc), vehicles, machineries, lands, and other properties.

The formal name for this process is called an initial public offering or IPO. Typically, a company goes public when it needs to raise cash, usually for expansion. In exchange for cash, the original owner(s) of the company give up some rights and some measures of decision-making control to shareholders. The original owner(s) become peer owner(s) to the new shareholders.

The initial public offering process spells out the terms and conditions of the business entity. In a simplified term, it spells out how many total shares of the whole company, e.g., 400 million shares, and how many shares the original owner(s) get, and how many shares it is selling to the general public. It also spells out the offering price for each share that the company is selling to the general public.

The initial public offering process can issue three types of stocks: common stock, preferred stock and warrants, and within those three types of stocks, it can also issue multiple classes of a stock as well. Each stock whether it is a common stock or a preferred stock or warrants can contain classes such as common stock class A, B, C, etc., Preferred stock class A, B, C, etc., and all those combined shares in the three types of stocks is called shares outstanding in a company. So the shares outstanding includes the common stock shares, preferred stock shares and also the warrant shares.

The total of all those shares (or in the previous example, 400,000,000) is called shares outstanding. All those shares outstanding is called a stock, hence answering the question posed earlier 'what is a stock?'

Notice that a company can have many stocks: common stock, preferred stock and warrants, and each of the three types of stocks can contain classes of their own, such as common stock class A, B, C, etc., Preferred stock class A, B, C, etc.; and each class in those three types of stocks is also called a stock.

Now the answer to the question: 'what is a stock?' is now much clearer.

Different classes of a stock contain different rights and privileges, with the highest rights and privileges given to the highest alphabet order. For example, class A shares have higher rights and privileges than class B, class B shares have higher rights and privileges than class C, class C shares have higher rights and privileges than class D, and so forth.

Of the three types of stocks, common stock shares have the least rights and privileges and preferred stock shares have the highest rights and privileges and its classes shares generally have preferrential treatment over all common stock classes shares and also have preferrential treatment over all warrant shares of a stock as well. warrant shares generally have rights and privileges somewhere between common stock shares and preferred stock shares.

A share of a stock whether a common stock, a class A, B, or C, or preferred class A, B, or C, or warrants, represents a part-ownership in the company. A publicly traded company is owned by its shareholders, including the original owner(s) -- often thousands of people and institutions -- each owning a fraction of the whole company.

If the initial public offering process makes no mention of other classes of a stock, it is assumed that the initial public offering is just issuing only one class of a stock commonly called common stock.

Why do companies choose to have more than one class of stocks?

There is typically only one reason that companies choose to offer multiple classes of stocks, and that is, to entice investors to buy more shares of the company -- and therefore, to raise cash to run the company. To raise cash, companies need to use gimmicks like offering investors with certain classes that pay dividends, having preferrential treatments, and other perks. You will often see a lot of non-high growth companies offer multiple classes of stocks, whereas high-flying growth companies rarely have more than one class of stock because they have no shortage of investors wanting to buy their shares.

Open Trading Visibility

When a company goes public, it also benefits from the fact that its stock is trading in the open market. This open trading tends to give the company legitimacy: its performance, its financial vitality becomes visible to all critics and non-critics.

When a company goes public, the value of the company is determined by the general public. That is, the general public take a look at the company's total shares outstanding and the offering price for each share that the company is selling to the public and multiply them together to get the total value of the company.

For example, if the company's total shares outstanding is 10,000,000 shares and the offering price for each share that the company is selling to the public is $10 per share, then the total value of the company is $100,000,000 (10,000,000 X 10).

If the general public think that the company is worth at least that much, they would be willing to own some shares of the company. On the other hand, if the general public don't think that the company is worth that much, then they would not be willing to own any share of the company. It follows the modern understanding principle that the value of a thing -- or in this case, a stock -- is determined by what one is willing to give up (such as money) to obtain the thing (or in this case the shares of a stock). It's a market value-based principle where value is determined against a trade-in.

Now that you know the background of how an IPO works, let's see a real life IPO process featuring companies of Twitter, Facebook, Google and Snap Inc.


IPO Journey
Here is an actual IPO process outlined chronically for a typical company going public. The featured company is Twitter, which went public in November 7, 2013:

How Does IPO Pricing Work?

The actual mechanics of what happens are somewhat complicated, but the basic idea is simple economics: the price is set as the number which balances supply and demand. In more detail, here is what happened for Twitter:

Each Twitter co-founder owns a percentage of the company and how much that percentage is determined from the letter of the agreement when they first formed the company. In the letter of the agreement, it states in percentage who gets how much of the company. The founders followed the letter of the agreement signed when they first started the company; and perhaps later, the founders decided to bring in some early investors (for example, venture capital firms and angel investors), and they, too, get a piece of the company (stated in percentage). This is called private placement. The money raised from the early investors went straight into Twitter's bank account and get used to run the company. So now there are more people who own the company and the founders' stake get smaller because they have to share the company with more people. So now Twitter is owned by the founders, the early employees, and some early investors.

When a company first started as a privately held company, in order to conform with the rules and regulations in conducting an enterprising business entity, it needs to register with the state or locale authority of its jurisdiction to begin conducting an enterprising business. In the filing application, it can decide to allocate the total shares outstanding of the company in actual number of shares or in percentage (as Twitter did). Most companies started out allocating its ownership in percentage, e.g., two owners, each owning 50% of the newly formed company. Or it can decide to allocate its ownership in actual number of shares, e.g., two owners with 10 million shares, each owning 5 million shares.

Businesses ownership structure is very flexible and easy to alter once you formed it and filed it. The easiest way to form a new company -- if you don't know whether to allocate ownership structure in actual number of shares or in percentage -- is to just allocate ownership structure in percentage and later you can change ownership structure from percentage to actual number of shares to reflect your situation, like Twitter did. You can alter your business structure at any time after you formed it; and better yet, your company doesn't have to go public in order to change its ownership structure. All you have to do is filing an 'application of amendement' with the state or locale authority of your jurisdiction and do business as usual.

Usually when a company decides to allocate its ownership in actual number of shares is because of convenience and practicality rather than costs or of other reasons. If a company has many employees and other vesting interest and wants to compensate them in stock options, issuing actual number of shares makes a lot of sense -- and a lot of companies in this situation often do issuing actual number of shares at its inception.

Issuing actual number of shares has other advantages, too, and that is, the vesting interest can trade (buy or sell) their shares in private transactions. This is similar to buying/selling shares in a publicly traded company -- but the only exception is, there is no SEC or other locale authority of jurisdiction you have to comply with their rules and regulations in conducting this kind of private transactions. It's a private placement matter conducting private transactions.

A newly formed company usually requires a "bylaw" written by the founders of the company. The bylaw states the rights and duties of the company. At a very minimum, the bylaw should issue certificates of stock ownership to the shareholders involved.

Here is what a typical certificate of ownership looks like:

ABC Corporation
Incorporated under the laws of the state of Minnesota

                                  Certificate Number: 1000

This certifies that Mary Q. Public is the owner and registered holder of twenty thousand
(20,000) shares of ABC Corporation, transferable only on the books of the corporation
by the holder hereof in person or by duly authorized attorney upon surrender of this
certificate properly endorsed.

IN WITNESS WHEREOF, the said corporation has caused this certificate to be signed by
its duly authorized officers of the corporation this 2nd day of October, 2018.



                                      ABC Corporation



                                      by president: ___________________________
                                                         John J. Doe

Prior to 2012, the only restriction for private companies operating in the United States was that a company cannot have more than 500 shareholders at any time while it was still operating as a privately held company. The 500-shareholders threshold was originally introduced in 1964 to address complaints of fraudulent private trading activities of company's shares because of no threshold limit of private shares. Prior to 1964 there were no limit as to how many shareholders a private company can have; so because private companies can have as many shareholders as they wanted it caused fraudulent black market activities underground to popup and the SEC stepped in and instituted the 500-shareholders threshold.

The 500-shareholders threshold rule was increased to 2,000 in late 2012 with the passage of the JOBS Act of 2012, after complaints by Facebook and other tech companies for restricting them from granting employees shares of stock.

Leading up to Facebook's IPO (May 18, 2012), Facebook experienced a huge number of shareholders that spilled over 500 shareholders due to the company's policy of granting employees shares of stock. At that time, the JOBS Act wasn't enacted yet and Facebook was forced to go public for being over the 500-shareholders threshold.

Since the JOBS Act, private companies have more room to breath regarding their shareholders threshold. This 2,000-shareholders threshold restriction applies to any private company with shares allocation of either percentage or actual number of shares. So a company's shares allocation is irrelevant for this restriction.

Remember that Twitter started out at its inception by allocating its ownership structure in percentage. Now they have to do more work by changing its ownership structure from percentage to actual number of shares.

Before the IPO, ownership of Twitter is partitioned into N equal shares, and each of the aforementioned people's stake in the company is determined by how many of these shares each owns. For example, N is around 475 million shares for Twitter. How did they come up with the number 475 million? There is no rule that says you have to have a certain number or ranges of numbers for any company. It's based on one's intuition, or in this case, the founders' intuition to realize that their company, Twitter, was worth at least $475 million at that time. Other companies might have less than 475 million and some others might have more than 475 million shares depending on how the owner(s) judge the sentiment of the condition of the market at that time. So for Twitter, the founders felt that Twitter was worth more than $475 million and they decided to choose 475 million for their company.

The number 475 million shares is not set in stone either; the company can decide to increase or decrease it any time from now on as it sees fit during its lifespan as an enterprising business entity. The company can file an 'application of amendement' with the state or locale authority of its jurisdiction to do either a 'split' or a 'reverse split' of the original number of its shares; to either increase the shares by splitting the current shares into multiple ratios; for example, a 2 to 1 ratio, which splits every share into two shares effectively doubling the current shares; or the company can do a reverse split in which it reduces the current number of shares; for example, a 1 to 2 reverse split, which cuts the current shares in half. The ratios of the split can be as small as it wants by making it in decimal fractions and it can be as large as it wants by increasing the numbers in the ratios. Another way of increasing the total shares of the company is to sell shares in the initial public offfering or issue more shares in the secondary offferings after it had gone public.

Selling more shares means creating more [new] shares to sell to new investors; and therefore, increases the total shares outstanding of the company. So the current shareowners don't lose any actual number of shares that they've already owned as a result of selling more shares; however, they will experience a shareholder dilution. [More on shareholders dilution in a little bit.]

Out of 475 million shares, Twitter cofounder Evan Williams owns 57 million of these shares, so he owns 12 percent of Twitter. Why did cofounder Evan Williams owns only 57 million shares out of 475 million? Well, he was one of many cofounders, plus early investors also got a piece of the company and thus the math works out to 57 million shares for Mr. Williams. So all the allocated shares to the cofounders and early investors must totalled to 475 million shares.

Now Twitter decides to "go public" via an IPO. The reason for doing so is to raise more money. As if private placement isn't enough money and people to share the company, Twitter decides to go public. In other words, it decides to bring in more people and provide the public with the opportunity to share in the ownership of Twitter. Why would the Twitter founders want to give away more part of their ownership in their company? Well, they are not giving it away: they are selling it, albeit the proceed goes to the company and not to the founders themselves. Whatever the public pays for partial ownership in Twitter goes straight into Twitter's bank account for general purpose use in the company. Notice that the original owner(s) and early investors receive nothing or $0 dollar from the proceeds for their hard work building the company to an ipo; nor do they get any money for any subsequent future secodary offerings. All proceeds go straight to the company and not to the founders or early or late investors. That doesn't seem fair, or does it?

For the founders of Twitter [or for any other company for that matter], the upside of this, is that Twitter becomes a richer company, and they can use the new money to develop the company into an even better and profitable company, making the company more valuable. The downside is that their stake in this more valuable company goes down. This is called shareholders dilution because the more shares you sell to the public the more new owners the original owner(s) have to share the company with and it drives the current owners' shares value down.

Take it this way: you own an apple tree that produces good delicious apples for sale and you bring in other people to be part-owner and share the output of the apples. Your current share of the apple will go down because you have to divide the output with other people now. Stock follows the same principle.

This is not the only time that current shareowners experience shareholders dilution. Whenever a publicly traded company decides to issue more shares called secondary offering -- and that is -- an offering after the initial public offering, the total shares outstanding will increase and thus making the current owners' percentage of ownership smaller in proportion to the overall total shares of the whole company.

[A side note: any offering whether it is the second, third, fourth, fifth, etc., is called a secondary offering, the offering after the initial public offering. A company issues secondary offering shares to raise cash to run the company. Likewise, a company buys back shares from the public and retires those shares to increase current sharesholders' value. Buying back shares have a reverse effect on shareholders' value from issuing secondary offerings.]

How do the Twitter founders decide the optimal solution to this tradeoff?

They talked it over among themselves and decided how much ownership they were willing to give up and how much money they were looking to raise. So they balanced the loss in ownership against the gain in the money raised. So they decided that they needed to choose two numbers: the number of new shares of Twitter to issue; and the price at which to sell these shares. There you go again: a shareholders dilution.

Remember that the original shares of Twitter as of now is 475 million and the founders are contemplating adding more shares to the already 475 million. If they decide to issue M new shares of Twitter and sell them for $x each, then Twitter adds $xM to its bank account, but everyone who already owns Twitter shares had their ownership in the company reduced by the factor N / (N + M). This is called shareholders dilution: it dilutes existing shareholders' value because there are more shares outstanding and perhaps there are more shareholders in the company. The more shares the company is selling the more dilute value for existing shareholders.

Let's think about this shareholders dilution principle for a moment. Let's start from the beginning when a company just get started. The owner(s) own percentage of the company, say four owners, each owning 25 percent of the company. And let's say the owners decided to issue 400 million shares for the whole company and each receives 100 million shares.

There would not be a dilution of shareholders' value if the four owners don't want to sell part of their company to new investors. Any time you sell part ownership of a company, it reduces your current ownership holding. And furthermore, the money received from the sales won't directly benefit the current owners. The money goes straight to the company's bank account to be used in the company's operations.

After the sale, the company's shares outstanding is increased from the original 400 million shares to the newly added x shares plus the original 400 million shares. Notice that the four owners didn't lose their actual number of shares that they've already owned as a result of sharing their company with new investors. The original four owners still own 100 million shares each. Bringing in new investors doesn't mean that some of the shares that they've already owned are taken away from them and re-distributed to new investors. That's not how it is usually done.

Although it is rare, the original owners can decide to do just that by clawing back portions of the shares from themselves and give them to new investors while also filing an application of amendement with the state or locale authority of its jurisdiction to account for the transaction and go on with business as usual without issuing new shares to pay the new investors. That kind of practice is very rare in deed in modern business transactions, but it is legal and nothing stops you from doing that.

Now if you understood the Twitter description thus far, you may have noticed that Twitter did exactly that by going back to the founders themselves and clawed back portions of their ownership percentage and allocated it to the early investors. It may have been that one founder got 40%, another got 30%, another got 30%, and the early investors asked to get a 10% or 20% or any number of percentage (in which I am not sure since this information was/is [still] private).

So to give the early investors their demands the founders had to recalculate their ownership percentage to reflect the accommodation of new investors. That means that the founders' actual ownership percentage had to come down proportionately to satisfy all parties involved. For example, if a new investor had asked for a ten percentage investment, each founder's stake would have decreased by a factor of [10 x 1/3] or 3.33% that reduces the sharholder #1 from 40% to 36.37% and for the sharholder #2/#3 from 30% to 26.67%. Add them all up: 36.37% + 26.67% + 26.67% + 10% = 99.71% (and rounding off to the whole number to 100%).

If later, more [late] investors want to invest in the company, the same process that just described is followed if the company allocates its ownership in percentage. Let's say that one investor wants to invest, say, a 5% stake in the company, each founder's stake and the early investor's stake would have decreased by a factor of [5 x 1/4] or 1.25% that reduces for the current stake of sharholder #1 from 36.37% to 35.12%; for the sharholder #2 from 26.67% to 25.42%; for the sharholder #3 from 26.67% to 25.42%; and for the (early investor or sharholder #4) from 10% to 8.75%. Add them all up: 35.12% + 25.42% + 25.42% + 8.75% + 5% = 99.71% (and rounding off to the whole number to 100%).

What happens if the company allocates its ownership in actual number of shares instead of percentage? Well, the normal process is to issue more shares worth the amount stated in the investment term. For example, if the investment term states that a new investor gets a 10% stake in the company, then 10% [of the current shares outstanding] worth of new shares will need to be issued and given to the new investor so that existing owners don't lose any actual number of their shares that they've already owned. Very straight forward.

Now to finish off the four owners example: Similarly to Twitter's founders, the original four owners' stake in the company got reduced and is no longer 25%, even though they still each own 100 million shares, and now their holding is reduced in term of percentage by 1/4 times the newly issued shares for each four owners. This is called shareholders dilution, a process of selling more ownership to new investors. It's not uncommon for a company to sell more shares years after it went public to raise more cash to run the company. This is called secondary offering. It is also can cause shareholders dilution. To offset shareholders' dilution, a company needs to generate more business and thus generates more profits and thus its stock price goes up and thus makes shareholders happy and thus current shareowners will forget about the actions that a CEO took when he/she issued more shares to raise cash.

[Now let's continue with Twitter]

Twitter needs to choose M first, because what x should be depends on M: x needs to be a price that the public would be willing to pay to own 1 / (N + M) of Twitter. In the process outlined below, Twitter chooses M in step (1) and chooses x in step (5).

Here we go:

1. Twitter decided to offer 70 million shares on the public market. This means that current shareholders of Twitter have their stakes decreased by a factor of 13 percent = 475 / (475 + 70), and that 13 percent of Twitter is up for grabs for the public or mainly for institutional investors. How did Twitter come up with this number? Its executives know around how much money they want to raise, and how much of their ownership they were willing to give up.

Based on the number 70 million, Evan Williams knew right away that after the IPO his stake in Twitter will decrease from 12 percent to 10 percent, but in his mind he thinks this sacrifice is well worth it. Twitter now advertises to institutional investors (via its underwriting banks, in particular Goldman Sachs) that 70 million shares of Twitter are on the table, and invites them to submit requests for how many shares they would like to buy.

The process of going public is a two-tier process: first, you let institutional investors buy shares from you (via the underwriting banks), and second, in turn, institutional investors (later) sell those shares to retail investors (like you and I -- who lack deep pockets that instutional investors have).

Notice that Twitter or any IPO-bound company don't spell out the offering price just yet, and they kept institutional investors in the dark and institutional investors have no official word on how much they will have to pay per share, but they can do their own analyses to come up with rough estimates. This is almost like a Dutch Auction process where you want to gauge the demand of the shares by inviting buyers to submit their bids to buy shares, stating how many shares and how much price they're willing to pay.

2. Meanwhile, the institutional investors are busy at work trying to come up with an optimal price to submit their bids. They pay close attention to market news reports to see if rumors abound. Lo and behold for Twitter, rumors circulated that the offering price will be in the $17 to $20 range. [A side note: You can keep tuning to market news and you often hear rumors about some IPO-bound company is expected to price its share in range]. And for Twitter, rumors ran wild!

3. Multiple reports: Rumors circulated that the offering price will be in the $23 to $25 range. By now, institutional investors got a fairly good idea of the price range they intend to submit their bids.

4. By November 5, 2013, institutional investors must submit their requests on how many shares they wish to buy. I call these "requests" and not "bids" because they can take many forms, ranging from the simple ("I want to buy 1 million shares, no matter the price") to the complicated ("If the offering price is between a and b, I want to buy X shares; if the offering price is between b and c, I want to buy Y shares; but in the event that Z occurs I do not want to buy any shares"). This process resembles a closed auction where bidders of an item submit their bids in writing stating the price range and the quantity of the items. A more accurate comparison is that this process is similar to a Dutch Auction process where you invite buyers to submit their bids to buy shares, stating how many shares and how much price they're willing to pay and the underwriting banks can choose to accept bids that fall in the optimal range.

Who are these institutional investors?

They are the "important" clients of the underwriting banks: the top pension funds, mutual funds, hedge funds, high net worth individuals, and long standing clients. Why do these investors get first dibs on an IPO?

Retail investors often complain this is not fair, but the (official) reason is stability: the argument goes that institutional investors (who are accredited, sophisticated, more experienced, and who have deeper pockets and capacity to take risk) create stability in the stock price by being the first to receive them. The alternative would be for Twitter to offer its shares to the entire world all at once on IPO day.

While this seems more fair, experience shows that this creates havoc: Twitter [or any IPO-bound company for that matter] is afraid that if it starts by offering its shares to Average Joe investors at the outset, the price will jump all over the place and the market will become anxious and confused. Moreover, the SEC fears that the "unsophisticated" Average Joes do not know how to deal with an IPO appropriately and are likely to lose their life savings by purchasing the stock in this unstable environment.

Personally, the current practice of letting institutional investors have their first crack at it is outdated and I think today's retail investors are sophisticated enough to avoid pitfalls. So I think it should open to all investors. After all, in the era of the information age, retail investors have access to all kinds of information, advices and opinions [on the internet], both for and against any IPO-bound company; and therefore, the majority of retail investors are more than well-versed about investing. That's just my opinion.

To back up my opinion, I intend to change the way they practice the "initial public offering" and allow basically everybody to have a crack at the IPO, assuming my company is good enough and worthy enough to go public. From now on, companies that I found will allow basically everybody to have a crack at the IPO, even if nobody else is following my trail and footsteps. Please stay tuned! A good place to tune to is:

http://www.noon2noon.net.
5. On November 6, 2013, around 4:00pm, after they've received all bids and reviewed and picked the optimal price: Twitter finally sets its IPO price at $26. By looking at the set price at $26 per share, we can see that the majority of the bids probably would've fell between $20 per share and $30 per share. So this means that anyone who submitted their requests at $26 a share or higher most likely will be granted as "winning" bids and anyone who submitted their requests below that price were rejected. At this point, Twitter knows that it will raise exactly $26 x 70 million = $1.8 billion in cash from this offering. We say that this offering price values the company at $14.2 billion = $26 x (475 million + 70 million). The only way you can say what a company is worth is by seeing how much someone else would pay for it, or at least how much he would pay for a share of it.

6. On November 7, 2013, around 8:30am: The IPO underwriters look at all the requests from step (4) and decide how to allocate shares to the institutional investors. This is not as simple as giving each institutional investor what they requested if their conditions were met.

First, the total number of shares requested by all institutional investors is likely much, much more than 70 million (and most institutional investors know that demand for shares greatly exceeds their supply, so they will tend to request a much higher number of shares than they actually want). After all, a lot of these institutional investors are dealers: they buy low and sell high to retail investors. So they will try to get as much shares as possible. And the best part, is that, they don't even have to send in the money right away. They can request the shares and when the IPO is open for trading for the first time, they can sell the shares at a higher price than they requested and pocket the difference.

Second, this is the only chance the offering company and the underwriters have to control what kind of shareholders have a stake in the company. They know the reputations/styles of the institutional investors, and they take this information into consideration when choosing how to allocate the available shares. The process is not "fair" in the sense that all of the institutional investors are on the same playing field; however, they're at the mercy of the underwriters who have full control of deciding who gets how much.

For example, the underwriters would be wary of granting a large number of shares to an investor who is likely to flip them (wait until the price spikes upon the opening trade and then immediately dump the position). The underwriters want an ideal balance of different types of investors: long term investors, short term investors, domestic investors, foreign investors, etc. Note that (essentially) all of the requests at this stage are "buy" requests; although in some cases an institutional investor can request to borrow shares (with the intent of creating a short position by selling them), this is very rare and (understandably) not very well received by the underwriters.

7. On November 7, 2013, before market open: All of the 70 million shares are in the hands of the initial institutional investors, who now owe Twitter $26 for each share they were granted. From here on, Twitter the company -- I mean the company and not the founders and early investors -- don't stand to gain a penny from the market activity. However, for the founders and early investors, they stand to gain/loss from the market activity.

8.On November 7, 2013, at the market open (9:30am): Orders start coming to the NYSE from all over the world, from both retail investors and institutional investors (both the ones who were lucky enough to be part of the initial offering and the ones who were not).

Each order is either a "bid" to buy ("I want to buy TWTR") or an "offer" to sell, also known as "ask", ("I want to sell TWTR"), with the latter presumably only coming from those [early] institutional investors who already have the stock to sell. Each order includes both a price and a size: for example, "I am willing to pay $45 per share for 100 shares of TWTR" or simply "bid: 45 x 100" or for an offer "ask: 45 x 100".

9. On November 7, 2013, after market open: The designated market maker (DMM) for Twitter (which is the bank Barclays) at the NYSE starts collecting all of the orders that are coming in. Taking a quick first look at the numbers they are seeing, Barclays reports that the prevailing price seems to be in the $40 to $45 range for the majority of the orders. This number is reported by the market news media [or sometimes called rumors].

10. On November 7, 2013, after market open: The DMM (Barclays) works on setting the opening price. The opening price is chosen so that supply and demand are balanced as well as possible. In other words, the opening price is the price that maximizes the number of trades that can be executed, based on all of the orders submitted thus far. This process is called price discovery, and is handled by humans at the NYSE (unlike Nasdaq, which handles price discovery electronically).

Once the opening price is decided upon (for Twitter, $45.10), the DMM "freezes the book", or blocks any new orders from coming in. Next, the DMM enters all of the accepted orders into the system, matching buyers and sellers based on the prices and sizes they submitted. The process of price discovery usually takes around fifteen minutes for the NYSE, but since Twitter is such a high profile stock with a great deal of anticipation and demand, the process took over an hour.

11. On November 7, 2013, at 10:50am: Bam, Twitter begins trading at $45.10. In particular, the public is willing to pay $45.10 per share of Twitter, and we say this opening price values the company at $24.6 billion = $45.10 x (475 million + 70 million). Twitter instantaneously increases in value by $10 billion.

12. On November 7, 2013, at market close (4:00pm): Twitter closes at $44.90.


Conclusion: Was Twitter a Success for its IPO?
The success of an IPO is measured by how smoothly steps (10) and (11) go. If the price during discovery falls below the initial offering price ($26 for Twitter), this looks embarrassing and the underwriters will shore up demand by purchasing shares. Similarly, if the price goes berserk once trading begins, the DMM is blamed for not setting the price appropriately.

The fact that the closing price ($44.90) is close to the opening price ($45.10) in this case is a sign of stability, and that the underwriters and the DMM performed their job well.

Note that for Twitter as a company, the exciting day was November 6, not November 7. On November 6, Twitter set the offering price, and thus knew it would raise $26 x 70 million = $1.8 billion in cash. The opening price ($45.10) is irrelevant here.

But for the employees of Twitter, especially the founders and early investors, the exciting day was November 7: they already owned shares before any of the IPO process happened, whether they obtained these shares as founders, as early investors, or in the form of employee compensation and those shares are worth a fortune. But they were in limbo regarding just how much this intangible stake in the company was worth until 10:50am, at which time they gleefully realized they now had $45.10 x n in their pockets, where n is the number of shares they owned.

So who profited from the surge from the offering price of $26 to the opening price of $45.10?

Not Twitter, the company.

Instead, its employees and the institutional investors from step (4) just received a huge return. Considering this circumstance, was $26 too low of an offering price? Perhaps. If Twitter had instead set the opening price at $45, and assuming that demand from investors was the same, Twitter could have raised nearly twice as much money for the company. However, the goal of an IPO is not just to make as much money as possible for the company; it is also to build a foundation of happy shareholders, and a shareholder is happy if he gets a nice return from his IPO investment. Normally companies try to set the offering price so that the initial investors earn something like 10 percent on IPO day, so in that regard the 73 percent return the initial investors received is on the high side.

As a concluding aside, let us consider what happened to Facebook, now infamous for its botched IPO. The initial offering price (offered to institutional investors) was $38 per share. After price discovery, the opening price on the NASDAQ exchange was $42.05 (an 11 percent spike, compared to 73 percent for Twitter).

After trading began, the stock started to drop back down toward $38. It very well would have gone below $38 were it not for the embarrassed underwriters who provided support by purchasing shares at $38. The closing price on IPO day was $38.23. Needless to say, the institutional investors who received first dibs on Facebook were not pleased. Nor were they when a week after its IPO, Facebook closed at $26.81. And that's not all: Facebook continues to drop gradually to as low as $12 a share in the span of two years later from its IPO debut.

What went wrong?

Numerous things:

  • Two days before the IPO, Facebook changed its mind about M (the number of shares it would offer). Though the mathematics is simple, this meant that all the major players who had planned on purchasing shares on IPO day had to recompute everything and update their plans.

  • Many of the initial institutional investors reported in the days before IPO day that they intended to sell some of the shares they would receive. Remember that a lot of these so called institutional investors are people just like you and I who look to make money in the stock market. Except you and I don't get the privilege to obtain IPO shares at no cost and sell at the IPO debut trading to make quick bucks. In other words, a lot of these so called institutional investors are opportunistic dealers who seek to make quick bucks using their privilege and well-connected status.

  • Facebook's initial offering price was much closer to the expected market price than Twitter's; as a result, the initial institutional investors in Facebook stood to gain much less on IPO day than the institutional investors in Twitter.

  • The period of price discovery took exceptionally long (trading opened at 11:30am) and the process was marred by technical difficulties before and after the start of trading: orders did not come through, and investors were confused about whether or not their orders had been executed or even received.

  • Extremely high volume (because of unprecedented excitement about Facebook) overwhelmed the NASDAQ servers, exacerbating the technical difficulties.

  • The excitement was not only unprecedented, but also excessive: many retail investors wanted to purchase shares of Facebook because they were convinced it was the next big thing (for many young people, purchasing Facebook shares was their first foray into the financial markets), but the reality was that the prices at which it was trading were ridiculously high compared to its profitability. When "virgin" retail investors (who had been promised that the stock price might increase by as much as 50 percent on IPO day) saw prices dropping, they grew anxious and sold their positions, exacerbating the selloff.

Because of the Facebook debacle, everything about the Twitter IPO was much more conservative (lower initial offering price, conducting a dry run of the IPO over the weekend to test all of the systems, using humans instead of electronics to handle price discovery, listing on the NYSE instead of the NASDAQ), and it seems this caution paid off, at least as of day one.


Google's IPO

Google's IPO, 10 Years Later

On August 19, 2004, Google GOOGL went public in a highly anticipated initial public offering that valued the six-year old company at what seemed to be an astronomical $23 billion, with a price-earnings ratio of 80, a mere six years after its founding. The company was already generating annualized revenue of $2.7 billion and profits of $286 million.

As of today, August 9, 2014, Google's market cap is $390 billion, with annualized revenue of $64 billion and profits of $13 billion. Google's market cap is the third highest of any U.S. company, with only Apple AAPL and Exxon Mobil XOM being bigger. Public market buy-and-hold investors have scored a "ten-bagger", earning a return of more than 1,000% over the decade or an equivalent of $100 invested then is now (August 9, 2014) worth about $880,000 [Sources: Amazon $250,000/2500 = $100 and $2.2 billion/2500 = $100.].

Google's IPO was unconventional, starting with a registration statement stating that the company was planning to raise $2,718,281,828, a number that confused the many journalists who hadn't memorized the number "e" to the ninth decimal place, as any serious quant would have. Famously, the letter from the Founders contained in the prospectus stated a corporate goal of "Don't be evil." Several years later, the company decided to honor this commitment by pulling out of China rather than agreeing to facilitate government censorship of search results.

Google bargained with its investment bankers to lower the fees that are charged, and paid 2.8% rather than the more normal 4% that a multi-billion dollar deal would normally face. Most IPOs, and almost all of those that raise $50-200 million, pay their bankers 7% of the proceeds.

Unlike most IPOs, the company used an auction called a "Dutch Auction" to sell shares. The merits of using an auction versus the more traditional way of selling shares, known as bookbuilding where you let investors submit their bids and the company gauges the sentiment of the offering to if investors' appetite is high or low and chooses to set the price of the IPO accordingly.

An auction, at least in theory, should deliver the highest possible price for the company while giving individual investors, rather than just the fund managers who dominate the bookbuilding approach, the opportunity to buy shares. But by the time Google launched the IPO, it had scaled back the size of the stock sale and lowered the offering price in the face of weak demand. After setting a price range of $108-135 per share, Google went public at only $85 per share, selling just 22.5 million shares and raising just $1.9 billion.

Adding insult to injury, the stock rose 18 percent on the first day of trading to close at $100.34 -- suggesting that the auction failed to achieve its purpose of setting a price as close as possible to the value investors would award the stock on the open market. The IPO was largely viewed as a fiasco.

Part of the reason that the offering raised less money than expected was simply bad luck: In the weeks leading up to the IPO, both the technology-laden Nasdaq market and shares of Yahoo YHOO, Google's top rival at the time, had been drifting downwards, sending a chill through the IPO market.

Two other factors, however, were even more important. The first factor was that the "road show" did not go well. When a company goes public, in an attempt to stimulate demand, the top managers and the investment bankers hired to take the company public typically spend up to two weeks going from city to city making presentations to institutional investors and answering questions. Google's management, however, refused to answer many of the questions that were asked. As a result, investors were less willing than normal to give the company the benefit of the doubt about its future profitability.

The second factor that lowered the offer price was the desire of the lead underwriters, Credit Suisse and Morgan Stanley MS, to sabotage the auction. Underwriters find the bookbuilding system (also known as a "status quo" system) to be very profitable, and most feel threatened by auctions. With an auction, the underwriters no longer have the power to allocate underpriced shares to their favorite customers. Consequently, the lead underwriters didn't want the auction to be viewed as a success.

They didn't want it to be a complete failure, however, since they were the lead underwriters. The underwriters told many institutional investors that they were likely to receive shares if they bid $85 per share. Not surprisingly, there were a huge number of bids for shares at $85, and relatively little demand at a higher offer price. Google was forced to accept just $85 per share.

Google and the selling shareholders thus raised less money than they could have in the IPO. But the offer was selling only 8% of the company, and the employees and others who held their shares were amply rewarded as the stock rose, and rose further, as profits increased from $286 million per year to $13 billion per year. Google has proven that targeted search advertising can be an enormously profitable business, which is why Facebook was able to get a valuation of $104 billion when it went public in 2012.


Snap is Going Public

Snapchat is about to make a 26-year-old one of the richest people on Earth

Here is an article taken from a Vanity Fair Magazine dated February 17, 2017, by Maya Kosoff:

Here's how much money CEO Evan Spiegel will make when Snap goes public.

Next month, Snapchat parent company Snap will begin selling shares on the public market in one of the most highly anticipated I.P.O.s for a tech company since Twitter went public in 2013. With Uber and Airbnb still raising funds and bolstering their bottom lines as they mull public offerings of their own, Snap is expected to serve as a bellwether for the otherwise slow-moving tech-IPO pipeline and a critical test of the public appetite for other unprofitable Silicon Valley unicorns.

When Snap does go public, the company said in documents filed with the SEC on Thursday, it will price its I.P.O. at $14 to $16 per share, with a total of 200 million Class A shares. At that price, the offering could value Snap at $22 billion -- an eye-popping valuation given its recent losses, but still on the low end of its private-market valuation.

CEO Evan Spiegel, 26, and co-founder Bobby Murphy, 28, stand to make about $5 billion off of their shares in the company when it does finally go public, beginning with the $256 million in stock that they each plan to sell when Snap debuts, according to the documents. Both Murphy and Spiegel are the biggest shareholders in the company, and together they will control about 89 percent of voting rights in Snap once it's a public entity. (Their third co-founder, Reggie Brown, was paid $157.5 million in a settlement with his estranged co-founders after he filed a 2013 lawsuit over being forced out of the company.)

For Snap's I.P.O., Spiegel took a page out of Facebook CEO Mark Zuckerberg's playbook, consolidating the executive power at the helm of his company ahead of its offering, and offering shares without any voting power, allowing Spiegel and Murphy to retain control even after selling huge amounts of stock.

"Our two co-founders have control over all stockholder decisions because they control a substantial majority of our voting stock.... We are not aware of any other company that has completed an initial public offering of non-voting stock on a U.S. stock exchange. We therefore cannot predict the impact our capital structure and the concentrated control by our founders may have on our stock price or our business," the filing said.

Co-founders Spiegel and Bobby Murphy each own 20 percent of Snap, according to the prospectus. Based on a valuation that could reportedly reach $25 billion at the time of the offering, each of them would own shares worth about $5 billion. The two co-founders currently plan to sell 16 million Class A shares -- which don't have voting rights -- when the company goes public, with the expectation that will sell more over time.

Snap's co-founders aren't the only ones who will make money by shedding some of their shares during Snap's public offering. Shareholders like Snap chairman Michael Lynton, formerly of Sony, will sell up to 54,907 Class A shares, and make as much as $878,512 during Snap's IPO. Others such as Benchmark partner Mitch Lasky will make up to $171 million. Snap's earliest investor, Lightspeed Venture Partners, could make as much as $74 million. Once Snap goes public, Spiegel will also receive 3 percent of its stock as an award.

It remains to be seen how the public market will react to Snap, and whether it will emerge as a highly valuable, diversified social-media company like Facebook, or one that does well on I.P.O. day but flops afterward. Some potential investors have already "reacted with fury" over Snap's decision to sell shares with no voting power.

In the S-1 SEC's official filing for an IPO on Thursday February 16, 2017, Snap told investors it "may never achieve or maintain profitability." Snap also revealed that it will spend $2 billion with Google Cloud over the next five years, and that boss Evan Spiegel got nearly $900,000 of security services (or stock options) in 2016. The company sought in the filing to raise $3 billion.

"We have incurred operating losses in the past, expect to incur operating losses in the future, and may never achieve or maintain profitability," the filing said. Other similar companies, like Twitter, have also included similar language in their public offerings, and look what happens to Twitter now.

As of this writing (2/17/2017) Twitter's stock closed at $16.62 (USD) a share -- the lowest it ever been traded in its four years as a publicly traded company. It debuted on November 7, 2013 at around $45 a share and on January 3, 2014 its shares were trading around $70 a share and about a month later it began to head south and never looked back ever since. Will history repeats itself for Snap? We'll see!

SNAP INC (SNAP) IPO

Company Financials per S-1 SEC filing of 2/16/2017:

Snapchat's revenue growth is astounding -- and so are its losses. Here are the highlights.

  • Net revenue: $404.48 million in 2016, up from $58.66 million in 2015. That means the ephemeral messaging service grew revenue almost seven times in a year -- but its losses outstripped its revenue

  • Net loss: $514.64 million in 2016, wider than $372.89 million in 2015

  • Loss from operations: $520.39 million in 2016, wider than $381.73 million in 2015

  • Usage: 161 million daily active users in the December quarter (60 million daily active users in the United States and Canada)

  • Average revenue per user: $1.05 in the December quarter ($2.15 in North America)

  • Time spent: 25 to 30 minutes a day

  • Head count: 1,859 employees

Total Assets $1,722,792,000 (equates to Stockholders' Equity + Total Liabilities)

Total Liabilities $203,878,000

Stockholders' Equity $1,518,914,000

Pre-IPO Update: Snap tops expectations in pricing of long-awaited IPO:

Here is an article taken from Reuters dated: March 1, 2017 (one day to IPO)

By Lauren Hirsch (Reuters)

(Reuters) - Snap Inc priced its initial public offering above its target range on Wednesday (March 1, 2017), a source familiar with the situation said, raising $3.4 billion as investors set aside concerns about its lack of profits and voting rights for a piece of the hottest tech IPO in years.

At $17 a share, the parent of popular disappearing-messaging app Snapchat has a market valuation of roughly $24 billion, more than double the size of rival Twitter and the richest valuation in a U.S. tech IPO since Facebook in 2012.

The company had targeted a valuation of between $19.5 billion and $22.3 billion.

The book was more than 10 times oversubscribed by institutional investors and Snap could have priced the IPO at as much as $19 a share, but the company wanted to focus on securing mutual funds as long-term investors rather than hedge funds looking to quickly sell, the source said.

The source asked not to be named because the matter is confidential. Snap declined to comment.

The share sale was the first test of investor appetite for a social-media app that is beloved by teenagers and 20-somethings but faces a challenge in converting "cool" into cash.

Despite a nearly 7-fold increase in revenue, the Los Angeles-based company's net loss jumped 38 percent last year. It faces intense competition from larger rivals such as Facebook as well as decelerating user growth.

Snap priced 200 million shares on Wednesday night at $17, above its stated range of $14 to $16 dollars a share.

The sale had the advantage of favorable timing. The market for technology IPOs hit the brakes in 2016, marking the slowest year for such launches since 2008, and investors are keen for fresh opportunities. The launch could encourage debuts by other so-called unicorns, tech start-ups with private valuations of $1 billion or more.

Institutional investors bought the shares despite them having no voting power, an unprecedented feature for an IPO despite years of rising concerns about corporate governance from fund managers looking to gain influence over executives.

Snap is set to begin trading on Thursday on the New York Stock Exchange under the symbol SNAP.
Snap Initial Public Offering Procession

An IPO Procession Reminiscent of a Wedding Procession

Here is a chronically outlined ipo procession for Snap that reminiscent to a wedding ballyhooed procession which took place on Thursday March 2, 2017. The preparation and anticipation of an ipo mirror the wedding preparation and anticipation where things are orchestrated in an elaborate fashion; while the anticipation is high for both the guests and bride and groom and the same thing can be said for the ipo. Keep in mind that the similarity of the two doesn't end at the ipo. For a lot of companies it continues beyond the ipo -- Twitter comes to mind. Just as a splashy wedding is no guarantee of an enduring marriage, stock price of a hot and high demand at ipo says little about a company's long term prospect.

Mar 2, 2017 at 8:10 am ET

As we get set for the trading to begin, here are some facts that we know so far about the IPO:

Snap is the parent company of Snapchat, an ephemeral, or disappearing, messaging platform that is very popular among the millenials, age 18 to 24 years old. Snapchat is a one-to-one and group messaging app that lets users (particularly millenials) send photo, video, and text messages that disappear after several seconds. Roughly 150 million people use Snapchat every day, and they consume around 800 hours of video per second.

The History of Snapchat

Three Classmates Meet at Stanford University

Evan Spiegel, Robert "Bobby" Murphy, and Frank Reginald "Reggie" Brown IV, who was pushed out in 2012, met at Stanford University around 2010. At that time, Spiegel and Brown were juniors; while Murphy had graduated. Spiegel (who eventually didn't graduate) studied product design, Murphy studied mathematical and computational science, and Brown studied English. All were members of the Kappa Sigma fraternity, for which Spiegel served as social chair. At the Kappa Sigma fraternity that the trio got to know each other well and they started to hang out together throughout their college days.

In the summer of 2011 after they all left Standford, the trio began work on an ephemeral messaging app they soon dubbed "Picaboo." The co-founders built a prototype at the Los Angeles home of Spiegel's father, assigning a title to each: Spiegel, CEO; Murphy, CTO; Brown, CMO.

Soon after that things turned sour for the three founders and Reggie Brown was pushed out in 2012. In February 2013, Reggie Brown filed a lawsuit against his former co-founders. In September 2014, Reggie Brown was paid $157.5 million in a settlement to close off a 2013 lawsuit he had brought against other co-founders Evan Spiegel and Bobby Murphy, alleging that they had taken his original idea and run with it, pushing him out of the company without compensation in the process.

So Long, Picaboo. Hello, 'Snapchat'

The name "Picaboo," it turns out, is a name already in use by an older New Hampshire-based company that published and printed images. In September 2011, Spiegel, Murphy and Brown rebranded the app changing its name from Picaboo to Snapchat, added the ability to caption photos, and relaunched in the iOS App Store. They focused on the app's technological innovations more than branding and marketing to make the experience more organic and cool than traditional advertising.

Fast Forward

Snap priced 200 million shares on Wednesday night (March 1, 2017) at $17, above its stated range of $14 to $16 dollars a share.

Recent disclosures and decisions have led to more over/under speculation on its IPO than on a college football game. The book was more than 10 times (or more than 2 billion shares) oversubscribed by institutional investors, which means that the deep-pockets investors are fighting each other to get the shares. It also means that there will be a lot of these instutional investors who got shut out in the allotment process will try to be the first one in line to "snap" up the shares when it opens for trading for the first time. So look for an openning "pop."

Snapchat parent Snap valued at $24 billion after better-than-projected IPO pricing on Wednesday night, as investors clamored for a piece of the biggest technology IPO in the U.S. since Alibaba made its debut in 2014.

For Snap, the truth will be in advertising-Herd on the Street

Snap calls itself a camera company, but everything beyond the first line of its IPO filing suggests it is an advertising company. And estimating how much ad revenue it can generate is essential to determining its value.

Snapchat Founders Keep Control

In the IPO of Snap Inc., new investors will get zero votes while Evan Spiegel and Bobby Murphy, the Snapchat creators, will have 70% voting power; deep-pockets pre-IPO investors get less-powerful voting shares.

Snap CEO Paid More Than Rivals in Year Leading to IPO

Snap CEO Evan Spiegel took home more cash in the year leading up to the company's IPO -- without accounting for inflation -- than the CEOs of Match Group, Facebook, Pandora Media, ETSY, LinkedIn, Twitter and Square, ahead of all of those companies' public offering, a new study says.

In 2016, Spiegel's salary from Snap was $503,205, the study conducted by Equilar says. Facebook CEO Mark Zuckerberg received $483,333 in 2011, the study says.

Spiegel also received the largest CEO bonus, of $1 million, of any of these CEOs in the years before their companies went public, according to the study.

Will Snap's IPO Crackle or Pop?

To become the next Facebook instead of the next Twitter, Snap must accelerate user growth and keep monetizing its existing users.

Snap is asking a lot of its investors in its coming IPO, and that may lead them to push back.

Mar 2, 2017 at 8:19 am ET

The Steps Snap Took to Bolster Demand

Snap executives took some unusual steps that could help bolster demand for the shares.

In a regulatory filing ahead of the IPO, the company said roughly one-quarter (or 50 million shares) of its planned float of 200 million shares would be subject to a lockup of one year before that chunk could be sold.

The company planned to sell those shares (about 50 million shares) to a group of existing accredited deep-pockets investors, who got in before the IPO process began, people familiar with the deal said. Other [accredited] deep-pockets investors would be locked up for less time. Such moves could damp volatility by limiting the number of short-term stockholders known as "dealers" [who buy low sell high] who can jump in and out.

In the offering, which raised $3.4 billion, about 120 million of the shares sold went to roughly 25 investment firms, according to people familiar with the offering. The 50 million shares going to the group of existing [accredited] deep-pockets investors meant there were only about 30 million shares to be distributed among all other interested institutional investors, the people said.

Mar 2, 2017 at 8:36 am ET

Hard to Imagine Better Timing for Snap's IPO

Investors are hungry to buy just about any stock these days and portfolio managers are particularly starved for new supply of fast-growing shares of information technology companies.

Demand is evident in the pricing of Snap shares sold to big institutions at higher-than-expected value of $17-a-share.

Meanwhile, U.S. stocks are plowing higher and no group of S&P 500 shares are faring better than than information technology -- up 11% in just over two months, compared with a 7% advance for the benchmark.

"All stars are lining up for this thing. It couldn't be more ideal," said Josef Schuster, founder of IPOX Schuster, a research firm that specializes in creating indexes tied to IPOs.

Mar 2, 2017 at 8:57 am ET

Snap's Challenge: Monetize its Users Base

It seems pretty likely that Snap's IPO is going to look more like Facebook's than Twitter's, but from this point out, it's going to try and mimic Facebook's business, and not Twitter's.

The company has to expand its users base, while at the same time hiring away ad-sales reps from Facebook and Google, and then leverage those two planks to sell the advertising industry on its platform.

It seems that monetization of its user base is not something you could take for granted, especially not when you have to take the money from Google and Facebook. Which is what these guys now have to do.

Mar 2, 2017 at 9:03 am ET

But How Much Will It Pop?

Remember that a big chunk of Snap Inc.'s shares (about 50+ million shares) will be going to buyers who can't sell them for at least a year.

The lock-up could damp volatility by limiting the number of short-term stockholders who can jump in and out.

In a regulatory filing ahead of the IPO, the company said roughly one-quarter of its planned float of 200 million shares would be subject to a lockup of one year before that chunk could be sold.

The company planned to sell those shares to a group of existing accredited deep-pockets investors, who got in before the IPO process began. Other institutional investors would be locked up for less time.

Mar 2, 2017 at 9:18 am ET

Ceremony Surrounds Each NYSE IPO

It's one of the most cherished and orchestrated rituals of American capitalism: an initial public offering at the New York Stock Exchange.

For companies going public, the day begins with breakfast in a palatial ballroom upstairs from the NYSE trading floor. NYSE parent company Intercontinental Exchange recently finished a two-year, multimillion-dollar renovation of the ballroom and other event spaces in the historic building at the corner of Wall and Broad Streets in lower Manhattan.

NYSE officials present the firm going public with a certificate identifying it as a listed company on the 224-year-old exchange. And, of course, the firm's leadership rings the 9:30 a.m. opening bell.

Mar 2, 2017 at 9:21 am ET

Here is Why Snap's Shares Could Run When They Open

There's a lot of pent-up demand for new tech listings, which means Snap shares could run when they open on the New York Stock Exchange later today.

Ahead of Snap's IPO, there hadn't been a U.S.-listed tech IPO since December when Trivago NV debuted, according to Dealogic. The hotel-search company priced its IPO below its expected range, though shares did rise in its first day of trading. Last year was also the slowest year for tech IPOs in terms of money raised since 2009, Dealogic data shows.

Mark Hesse, analyst at Nuveen Asset Management who was considering buying shares of Snap ahead of its IPO, said he expects Snap could pop right out of the gate based on this hunger for tech IPOs. Mr. Hesse said he also is upbeat on Snap's business.

"There's a real opportunity to grow," he said, referring to Snap's advertising revenues.

Mar 2, 2017 at 9:23 am ET

What Happens Before Snap Starts Trading?

Note that even though Snap executives will be ringing the opening bell in about 10 minutes from now, trading in Snap won't begin right away. First there's an auction process where institutional investors who didn't get in on Snap during the pre-IPO phase try to be first in line to buy Snap's publicly traded shares. Their demand is met by sellers of Snap shares, including the bank(s) selected as the so-called "stabilizing agent," which Goldman Sachs is the leader among them.

This auction procession is overseen by a firm called the designated market maker, or DMM, whose lead trader stands on the NYSE floor, surrounded by a huddle of floor brokers representing big buyers and sellers.

Each company listed on NYSE gets to pick its DMM ahead of the IPO. There are now six DMM or "specialist" firms active on the NYSE floor, down from dozens in decades past. Snap's DMM will be Global Trading Systems, a New York-based high-frequency trading firm that acquired the NYSE floor operation of British bank Barclays PLC last year.

The DMM's lead trader shouts out prices so the floor brokers know how the auction is coming along, while in a parallel process, an algorithm matches buyers and sellers electronically. The auction ends when the DMM, working with the stabilizing agent, settles on the opening price. Then the shares begin trading. NYSE officials say this usually happens by around 10:00 a.m., although for some high-profile IPOs - such as those of Twitter Inc. and Alibaba Group Holding - it can take a couple hours for trading to start.

Mar 2, 2017 at 9:25 am ET

Quiet on the Floor

Right now it's pretty quiet on the floor of the New York Stock Exchange.

The exchange asked all non-necessary personnel to stay off the floor because about 100 Snap employees and friends are expected to be here for the bell ringing. Snap co-founder and CEO Evan Spiegel will ring the bell, but then he'll drive over to Goldman Sachs headquarters to watch the traders there open the stock in their role as stabilization agent.

Mar 2, 2017 at 9:27 am ET

Snap Is Wildly Uncertain for Investors

Morningstar analyst Ali Mogharabi launched coverage of Snap late Wednesday, warning that there's a lot of uncertainty around the name, particularly with the high price of the shares.

The analyst writes: "The IPO price is modestly above our fair value estimate and we would recommend a wider margin of safety before investing in this very high uncertainty name." He adds: "we are not yet convinced about the firm's ability to generate excess returns on capital over the next decade."

Morningstar's doubts come from the fact that, "there is no guarantee that a larger portion of new digital ad dollars will flow to Snap." In particular, they believe Facebook and Alphabet's Google, which have more developed ad platforms, are likely to keep raking in more of that money.

Still, the short-term traders who will be jumping into the stock when it begins trading Thursday may not be thinking that far down the road.

Mar 2, 2017 at 9:40 am ET

How Unusual Is Snap's Share Structure?

First, Snap IPO has no voting rights. That is very unusual. How unusual? Dealogic does not tracked that data point, so nobody can say for sure, but the data provider says it is very unusual.

Dealogic does track dual-class share structures, which Snap has. How unusual is that? Only 14% of IPOs since 2010 have had dual class shares. But that does rise for tech IPOs. According to Dealogic, 24% for tech IPOs .

So Snap is in the minority but it's not unusual among Tech IPOs.

Mar 2, 2017 at 9:43 am ET

Watch Shares of Twitter, Facebook on Day of Snap's Debut

As the stock market opens, keep an eye on shares of Twitter and Facebook.

While Snap called itself a camera company in its regulatory filings, many investors looking at the deal scoffed and said it remains a social media company in their eyes.

Some traders and investors said to watch to see if any "pairs trades" are placed today in relation to Snap and Facebook or Twitter.

A pairs trade is a strategy that involves taking a long position and a short position in two companies that are in the same sector and sometimes can be viewed as competitors (for instance, a pairs trade could be taking a long position in Visa coupled with a short position in MasterCard).

Alternately, some traders said to watch for investors who believe in Snap's ability to grow users (and revenue per user) who may be dumping Twitter's stock in favor of scooping up shares of Snap.

Mar 2, 2017 at 9:44 am ET

Facebook Lower, Twitter Higher as Snap Auction Gets Underway

Other social-media shares are mixed as Snap Inc.'s auction process gets underway.

Facebook Inc., owner of Snapchat rival Instagram, is down 0.2%. Twitter Inc., whose growth trajectory Snap hopes to avoid, is up 0.5%. The Global X Funds Global X Social Media ETF (of course there is one) is down 0.8%.

Mar 2, 2017 at 10:03 am ET

Snap's First Indication: $21 to $23

The first pricing indication (or rumor) for Snap has leaked and crossed the wire: $21 to $23 a share.

Mar 2, 2017 at 10:08 am ET

For Those Keeping Score...

Snap Inc's initial pricing indications point to a first-trade pop of between 24% and 35%.

The leaked rumor initial price range laid out in the frantic auction procession is $21-$23 compared with the IPO price of $17.

Mar 2, 2017 at 10:11 am ET

It May Take a While for Snap to Start Trading

The stock market is now open, but don't expect Snap shares to start trading right away as the "specialists" are frantically processing the buy/sell incoming orders, mostly from the institutional investors who got shut out at the pre-IPO process.

Basically, at this point specialists must work to match up people who want to buy the stock at the open with those who want to sell. This price-discovery process takes time.

For smaller IPOs, it can be fairly smooth, with new companies starting trading within the first half hour of the trading day. The bigger the IPO, and the more hotly demanded, the longer this process can take.

One trader on the NYSE floor predicted Snap doesn't start trading until at least 10:30 or 11 a.m.

That wouldn't be unusual. Alibaba shares, for instance, didn't open trading until nearly noon (the first trade was 36% above Alibaba's IPO price). Twitter took til nearly 11 a.m. to post its opening trade (which was 73% higher than its IPO price).

Mar 2, 2017 at 10:17 am ET

Keeping a Watchful Eye on the Auction Procession:

Snap's Updated Price Indication: $22 to $24

As the opening auction procession for Snap shares continues on the exchange floor and elsewhere, another pricing [rumor] indication has leaked across the wire: $22 to $24 a share.

Mar 2, 2017 at 10:28 am ET

Snap Sold 20% of Its Shares Outstanding

Snap floated about 20% of its outstanding shares. On average, tech companies that have gone public since 2010 have sold 19% of their shares in their IPO, according to Dealogic. Facebook sold 20%, Alibaba sold 15%, Twitter sold 15% and Google only 8%.

Mar 2, 2017 at 10:35 am ET

Oh, Snap! Not so Snappy!

Investors are still waiting for shares of Snap Inc. to launch into the secondary market and how much longer?

Mar 2, 2017 at 10:58 am ET

Snap Decision: Investors Bid Up the Wrong Snap Shares

Some trigger-happy buyers may end up pretty disappointed with their Snap purchase... if they're among the traders that have snapped up shares of Snap Interactive Inc. today or since Snap made news about their IPO-bound announcement.

Snap Interactive, ticker STVI, is up 18% at the moment. The problem is, Snap Interactive is not Snap Inc. It doesn't own Snapchat. And it isn't debuting on the New York Stock Exchange.

Snap Interactive, a public company since 2006, operates dating apps. It shares have tumbled from above $50 in 2012 (adjusted for a reverse split) to under $5 in January, but they've shown some unusual price movement lately since Snap Inc made news that it's going public. This is fairly to say that it's not a co-incident and suggests that almost certainly thanks to investor confusion about what the company does exactly. They're confused thinking they're buying the right Snap.

Folks, this is called "animal spirit" at its finest!

Mar 2, 2017 at 11:08 am ET

Party Poopers: Snap Doesn't Plan Big IPO Party for Employees

Snap hasn't organized any company parties to celebrate the company's public offering for workers in San Francisco or Los Angeles, employees say.

Instead, some employees watched the opening bell from home and individual departments have made dinner reservations.

Snap has not made any company-wide warnings to employees about flashy celebrations of new wealth, an employee says, despite a small protest outside the company's offices over rising rents in the artsy beach town of Venice where Snap has its largest offices.

Mar 2, 2017 at 11:13 am ET

Meet A Big-Time Snap Bear

Trip Chowdhry is a tech analyst and co-founder of Global Equities Research.

Mr. Chowdhry is also a Snap Inc. bear.

He writes this morning that that the hype around the disappearing-photo app company has the hallmarks of duds Fitbit Inc., GoPro Inc, Zynga Inc., Groupon Inc. and Twitter Inc.

Like all of the above, he says that Snap will likely beat analyst estimates for a few months, giving early investors cover to exit at higher prices. Then it could come crumbling down.

He writes that, for one thing, the disappearing app niche is assailable by rivals such as Facebook Inc.'s Instagram:

"The popularity of SNAP is based on a set of filters and the disappearing act of pictures, which is a flimsy foundation. Instagram can easily include these features and given its higher number of users; it will only get more popular if it does that." He goes on that it would be wise to avoid buying this stock now or else buying and getting the heck out while the going is good: "SNAP is not a multi-year story. The investing horizon should be in months not years.

Let all the hot air go out, let the private investors cash out, let's see how the Industry evolves in 1.5 years...and then if all looks good, then maybe invest in SNAP."

In a research note earlier this week he was even more direct:

"Speculative investors, if [they] decide to play the IPO, it will be prudent to get out of it within the 1st hour."

Mar 2, 2017 at 11:20 am ET

The Much Ballyhooed IPO

Snap Opens at $24 a Share

Sigh of relief .... Snap Inc. has begun trading.

The opening price: $24 a share. That's an immediate 41% pop for the deep-pockets institutional IPO investors who paid $17 last night.

Mar 2, 2017 at 11:21 am ET

Snap's Market Value at the Open: $33 Billion

And we're off! Snap's first trade hits that tape at $24, up 41% from its $17 price. It traded up 43% recently.

Snap's opening price gives the company market valuation of $33.3 billion on a diluted basis.

Mar 2, 2017 at 11:47 am ET

How Trading Volume Stacks Up So Far

Snap's trading volume has been brisk in the first hour as a public company.

Roughly 84.9 million shares have changed hands as of 11:42 a.m. ET. That's more than double the 36.4 million shares of Apple traded all day yesterday, on Wednesday.

Of course, this is no normal day for Snap, so volume is expected to be elevated. By comparison, here's how some other recent high profile tech companies stacked up on their first days. For Facebook and Alibaba, those days remain the highest volume ever.

Snap hasn't surpassed any of these tech companies yet, but the day is still young.

Mar 2, 2017 at 12:10 pm ET

Orderly Trading So Far

Despite the volume, the stock is trading in an orderly fashion. Snap shares have gone as high as $25.42 and as low as $23.50, but the trendline--so far, is up. Already, 117 million shares have traded hands.

Even at the low, hit a few moments after the shares started trading around 11:20, the price represents a healthy pop from its $17 per share IPO price.

An average based on how many shares traded at each price point, called VWAP, is at $24.62.

Mar 2, 2017 at 12:28 pm ET

What's Snap Actually Worth? One Analyst Says $10 a Share

In the face of a raging bull on Snap shares, Brian Wieser, an analyst at Pivotal Research Group, isn't big on Snap at the moment. He initiated coverage with a sell rating, and put his price target at $10 a share by year end, less than half of where it's currently trading. And even that's a stretch, he said.

Why no love for the hottest tech IPO in years? He says: "It is significantly overvalued given the likely scale of its long-term opportunity and the risks associated with executing against that opportunity. Significant ongoing dilution from share-based compensation will likely represent an additional negative consideration for the stock."

While the company continues to innovate and offers investors a piece of its business expansion, it's facing "aggressive competition" from larger firms, and its core user base isn't growing particularly quickly, Mr. Wieser says.

On top of that, "Investors will also be exposed to what appears to be a sub-optimal corporate structure operated by a senior management team lacking experience transforming a successful new product into a successful company."

"Snap Inc. is becoming a public company just as its user growth and monetization growth rates are beginning to meaningfully slow," he says.

The limitations on stock gains echo what some other analysts have been saying:

The increase in daily active users is slowing. That means growth will be driven by monetization, which is likely to be difficult, per consultations with ad buyers. Facebook and Google aren't just rivals. They're much larger rivals. The company is priced at a very high valuation, which limits room for error.

March 2, 2017 at 1:30 pm ET

Snap Hits Fresh High

About two hours after share started trading, Snap is setting fresh highs, hitting $25.69 moments ago. Already, more than 150 million shares have changed hands. Snap's volume-weighted average price for the day is now $24.76.

Mar 2, 2017 at 3:06 pm ET

Snap Crosses $26 and then Pares Gains

Shares of Snap touched a new intraday high in afternoon trade, but have since pared their gains. The stock hit as high as $26.05. It was recently at $25.18.

A total of 186.5 million shares had traded just after 3 p.m. ET, topping Twitter's total first-day volume but lagging Alibaba's and Facebook's.

Last Updated Mar 2, 2017 at 4:00 pm ET

Snapchat's Roaring IPO comes to a Close

Here is a wrap up with a few last thoughts:

  • Snap closed at $24.48, up $7.48 or 44% from its offer price of $17. It's first day pop was bigger than Alibaba's, Facebook's and Google's, but smaller than LinkedIn's, Twitter's and Yelp's.

  • It opened at $24, up 7.00 or 41.2% at 11:19 AM.

  • Snap was the most actively traded US stock today, with more than 215 million shares changing hands today.

  • At its high today, it was up $9.05 or 53.2%, to $26.05.

  • Best first day pop for a U.S.-listed IPO that raised at least $1 billion since LendingClub's December 2014 IPO (LendingClub rose 56% the day it went public.)

  • At the close, its market cap is $28.33 billion based on the 1.157 billion shares count in the SEC S1 filing.

  • Snap's market value increased by nearly $9 billion on its first day of trading.

The After Thought

Mar 2, 2017 at 6:30 pm ET

Meet the Company That Bought Snap at 98 Cents a Share

A big winner from Snap's initial public offering that has gone (somewhat) unnoticed is venture firm IVP.

Unlisted in Snap's registration statement, the firm led an early investment round in the company at an adjusted $0.98 per share. In time, the firm pumped $110 million into the company for nearly 37 million shares, worth about $900 million on paper at the close of the first day of trading. The firm has shied away from discussing Snap with the press since its original June 2013 investment. But in an interview on Thursday, general partner Dennis Phelps disclosed the size of his firm's stake and said it declined to sell shares in the IPO.

Snap is a "rare breakout platform" that he thinks is "on track to rival Facebook in the new social [media] order."

That may be a bit aggressive considering Snap is still just a tenth of Facebook's size in terms of the number of daily active users, but Mr. Phelps remains bullish as he says Snap will prove one of the few places where ad buyers will be able to target millenials.

And here is an "eat crows" feel bad story:

This Guy Ignored a Get-to-Know You Email from Snap's Co-Founder in 2012

Duh! Even the smart money misses a good deal once in a while.

Venture investor Chris Sacca, an early Google employee that later made a fortune buying up Twitter shares, took the opportunity of Snap's initial public offering on Thursday to eat a little crow.

Mr. Sacca tweeted an email sent to him in November 2012 from Snap co-founder Bobby Murphy, inviting him out for lunch.

"We're currently living and working out of a house in the Palisades....I'd love to get your opinion on LA vs the Bay and building out a company..." wrote Mr. Murphy.

That was around the time Snap raised its Series A round of financing at an adjusted $0.11 per share.

It closed on Thursday March 2, 2017, up more than 200 times from that price. Namaste! .... Eating crows! Eating crows! Eating crows!


What is an option?
As the word implies, an option gives you a choice or option to do what you wish to do with the subject. In other words, an option gives you the right -- but not the obligation -- to do something. In the financial world, an option gives you the right -- but not the obligation -- to buy or sell a stock, futures, a commodity or other investment instruments. A stock option is a contract between two parties in which the stock option buyer purchases the right (but not the obligation) to buy 100 shares of an underlying stock at a predetermined price from the option seller within a fixed period of time.

Think of an option as a contract betweem two parties -- usually between a buyer and a seller. Two parties agree on the term of the deal and signed the agreement of the deal.

You may have heard in the corporate world, a company pays executives compensations in the form of a stock option. This is a common practice in the corporate world. The reason being this common is to encourage executives to make the company's stock price goes up by running the company more profitably.

What usually happens is that each year a company offers its employees -- usually executives and board members -- shares of stock at a specific price and those shares have to be exercised at/or before a certain date -- usually the year-end date (right around December) or sometimes several years down the road, depending on how the company structures its option contracts with its [executive] employees.

There are distinctions between a corporate stock option and a financial stock option. A stock option in the corporate world cannot be bought and sold in the secondary market; while a stock option in the financial world can be bought and sold (or traded) freely in the open market. For the rest of the description, we won't discuss the corporate version of the stock options -- but only the financial version.

Option Contract Specifications

All options [with the exception of the corporate version] fall into two broad categories: call and put options. In a simplified term, a call option is a long option -- you're betting the option will rise so that you can profit from the rising option. On the other hand, a put option is a short option -- you're betting the option will fall so that you can profit from the falling option. It's a little tricky and confusing when dealing with these two instruments. Hopefully the following descriptions will help you understand better.

The following terms are specified in an option contract.

Option Type

The two types of stock options are puts and calls. Call options confer (give) the buyer the rights to buy the underlying stock while put options give him/her the rights to sell them.

Strike Price

The strike price is the price at which the underlying asset is to be bought or sold when the option is exercised. Its relation to the market value of the underlying asset affects the moneyness (price movement) of the option and is a major determinant of the option's premium.

Premium

In exchange for the rights conferred by the option, the option buyer have to pay the option seller a premium for carrying on the risk that comes with the obligation. The option premium depends on the strike price, volatility of the underlying asset, as well as the time remaining to expiration.

Expiration Date

Option contracts are wasting assets (meaning they will expire) and all options expire after a period of time. Once the stock option expires, the right to exercise no longer exists and the stock option becomes worthless. The expiration month or period is specified for each option contract. The specific date or period on which expiration occurs depends on the type of option.

For instance, stock options listed in the United States expire on the third Friday of the expiration month for the monthly contracts. For shorter contracts, say, weekly contracts, they expire on every Friday. The length of the contracts are varied from one week to as long as two years for certain stocks and they are set by the exchanges.

Option Style

An option contract can be either American style or European style. The manner in which options can be exercised also depends on the style of the option. American style options can be exercised anytime before expiration while European style options can only be exercise on expiration date itself. All of the stock options currently traded in the marketplaces in the United States are American-style options.

Underlying Asset

The underlying asset is the security which the option seller has the obligation to deliver to or purchase from the option holder in the event the option is exercised. In the case of stock options, the underlying asset refers to the (100) shares of a specific company. Options are also available for other types of securities such as currencies, indices and commodities.

Contract Multiplier

The contract multiplier states the quantity of the underlying asset that needs to be delivered in the event the option is exercised. For stock options, each contract covers 100 shares of a stock; for 1 corn futures contract contains 5,000 bushels of corn; for 1 crude oil contract contains 1,000 barrels of crude oil, and so on, and so forth.

The Options Market

Participants in the options market buy and sell call and put options. Those who buy options are called holders. Sellers of options are called writers. Option holders are said to have long positions, and writers are said to have short positions.


Explanation: Call and Put Options

A call option gives you the right to buy the corresponding stock or futures contract at a fixed price until the expiration date. So if you own the right to buy a stock, you're said to be going long on a stock. You hope that the stock you own the right to will appreciate in value so that you can exercise your option.

You Can Buy or Sell "Call" Options

To buy a call option means that you're buying the right to own that stock in the future at a specific price. So you the buyer of the call option can decide to exercise option at any time prior to the expiration of the contract. Since you're the buyer, you must pay the upfront amount called the option premium to the seller. Remember that buying a "call" option doesn't require you to currently own shares of the underlining stock (unlike selling a "call" as you'll see in a moment).

To sell a call option means that you're giving someone else the right to buy the stock in the future at a specific price.

So you have to have the underlining stock (usually 100 shares per option) in your posession ready to deliver that stock to the buyer as soon as the buyer decides to exercise his/her option. You cannot sell a call option if you don't have that stock in your possession. This is the same as if you want to sell any items (such as clothes, foods, car, jewelries, etc); you have to have those items for sale in order for you to be able to sell those items. Call option applies to the same principle.

Actually, you can still sell call options without owning the stock by using leverage and this for options trading levels 2 and up. But for now just think that you have to have stocks in your posession in order to sell calls. Once you're comfortable trading options for awhile you'll know how to use leverage to sell calls and puts. But for this tutorial is to get you familiar with the basics and getting you started trading covered calls and secured puts. See my other tutorials on covered calls and cash-secured puts.

You might ask: why would anyone buys a stock and turn it around and allow someone to profit from your stock that you think that it is going higher? Well, the majority of investors are long term investors and they usually don't turn around and allow other investors to profit from their investment. But a small number of investors do buy stocks for the purpose of trading to maximize their investment. This is called "covered call" writing -- you buy stocks and turn around and sell the right to own those stocks to someone else; you're giving someone else the right to own your stocks.

In options, you can sell calls that you don't own as well, and this is called naked call. Don't worry too much about these two terms that I'm throwing at you because it is not significant right now. These terms are being used as options strategy that you can employ to maximize your profits. There are at least 128 options strategies available for trading and each strategy is tailored to specific play; for example, a bear put spread is an option strategy that allows you to profit when you think the stock has a neutral or bearish outlook within the time expiration. Other options strategies are: call credit spread, iron condor, bear put spread, bear call spread, bullish butterfly, half and half, straddle, strangle, leap, leap call, and more. My premium members have accessed to all these advanced strategies and much much more.

A put option is quite the opposite of a call option. A call option is an option to go "long", whereas a put option is an option to go short (or sell short) -- betting it to go down.

A put option gives you the right to sell short the corresponding stock or futures contract at a fixed price until the expiration date.

In a call option you have to have the stock in your posession or enough money in your account (if you're a seller), ready to deliver to the buyer. But in a put, you the short seller do not have to have shares of stock but rather borrow shares of stock from the brokerage firms and pay them back when the options are settled. Again, you don't have to have stocks in your posession in order to sell puts or selling short; however, you have to have enough money in your account to cover the contract involved in the agreement.

You Can Buy or Sell "Put" Options

In general, to short a stock you borrow shares from the brokerage and sell those shares immediately and wait for the stock to drop and buy back those shares in the open market when the stock price is lower than the price at the time you sold the shares. Your hope is for the stock to go lower at any time prior to the expiration date and buy the stock back at a lower price and pay the broker back and profit the difference.

Let's think about this principle a little bit: first, you think that the stock is going to go down. Second, you want to profit from the down side move of the stock. And third, you don't own the stock or know anybody that own shares of that stock. So what do you do? If you have a position on that stock, you better sell that stock very quick or else you're going to lose your money on that holding if your prediction is correct. So if you don't have a position in that stock but you definitely want to have an action on that stock. What do you do?

An answer to that question is to borrow shares of that stock from a broker since the broker has his/her clients holding on to that stock. Once you borrowed the shares you turn around and sell those shares right away and keep the proceed in the broker's account and wait for the price of the stock to drop so that you can buy those shares back and return those shares to the broker so that the broker can credit his/her clients' shares to the original record.

His/her clients think that the stock is going to go up but you think that the stock is going to go down. A difference of opinion. Either the clients are right or you're right: both of you cannot be right.

So if you think that you're right, why not try to profit from someone else mistake? In this case, the clients who think that the stock is going to go up and so you are going to try to eat their lunches. So the clients own the shares and you own nothing, but you want an action on that stock. So you go to your broker and say, "Listen, fella! -- your clients have shares of this stock, can you lend me those shares and I'll pay them back those shares when the stock price drops."

Do you see what's going on here? You borrow the shares from your broker's clients and turn around and sell those shares in the open market. In reality, the borrowing and selling of the borrowed shares exist only in one transaction via the broker's account. Think of it as a three-parties transaction account where a broker (party 3) steps in and acts on behalf of either the shareowner(s) (party 1) and the short seller (party 2) to transact the deal.

For example, in the case of a short selling, a broker steps in and acts as a shareowner using his/her clients' shares to allow the short seller (or party 2) to sell short on those shares without the knowledge of the shareowner(s). The shareowner(s) could careless what their broker do to their shares of the stock as long as they still own those shares and can liquidate them at any time.

So the broker steps in and allows you, the short seller, to sell someone else shares without the knowledge of the shareowner(s). Meanwhile, you, the short seller, wait for the price of the stock to drop so that you can buy those shares in the open market at a lower price and then return those shares back to the broker's clients and pocket the difference; while the broker's clients had no knowledge of the transactions behind the scene and still lose money regardless you borrow those shares from them or not. They still lose money on their long holding because they were wrong and you were right.

So from the clients' perspective, they don't care whether you borrowed their shares of the stock or not -- it made no difference -- they still lose money. So keep this 'short-selling' principle in mind when you're dealing with put options. Now what happens if you're wrong and the clients are right? Well, the clients will eat your lunches -- the same way you eat the clients' lunches if you're right and the clients are wrong. Another way of saying is that you'll lose money and the clients will gain money.

You might wonder that no brokers will let you borrow their clients shares to sell because you're not a big shot wealthy person. Fear not; brokers will love to take commissions from you. The more shortsellers there are the more money brokers make through commissions because shortsellers are very active traders while long position investors rarely buy or sell; and thus generate less commisssions for brokers.

Short Selling Folklore

Okay, now that you know how short-selling works, it's time for a short-selling folklore. Do you know who created the principle behind short-selling that is being widely used throughout the world? Was it some geniuses mathematicians? Or was it some Noble Prize winning economists? Or was it some Ivy League academic professors? No, none of the above, and here's a folklore story:

A guy opened a retail brokerage firm and placed ads to encourage investors to buy stocks so that the brokerage retailer can make money by charging fees when investors buy and sell stocks. Mr. and Mrs. Jones came in and invested their lifelong fortune -- a lot of money -- in one company [presumably on a very solid and stable company], paid the fee to the broker and walked away. Meanwhile, the broker was very happy to have the Joneses as the client and hoped that sooner or later the Joneses will want to diversify and break up their large holding into different investments, creating more fees for the broker. So the broker waited, waited, waited, and waited, and waited! Five, ten years gone by and the Joneses was oblivious to the broker's wish and stayed put with their holding. [The length of time in five, ten years are fictional]

The broker got restless and decided to call the Joneses to encourage them to diversify their holding. But the Joneses didn't take the broker's advice and kept all of their holding in one company. The broker became even more restless and tried to come up with all kinds of tricks to make the Joneses break up their holding and diversify. One trick after another and the Joneses didn't budge and fell deaf ears to the broker. The broker wondered, "There got to be a way to make money off the Joneses."

If the pattern continues there will be 60, 70, 80, 90, 100 or more years before the Joneses sell their holding [the length of time are fictional.] There got to be a way to profit from the Joneses. Lo and be hold, the broker wondered to himself, "Why not let someone else sell the Joneses' holding if the Joneses don't want to sell? And charge the sellers fees instead." "Hello!, wake up fool!," the broker said to himself after realizing a clever way to beat the Joneses. "Finally, I can eat the Joneses' lunches!," the broker cheered to himself. [End of the folklore]

Now let's continue talking about put options. Put options follow the same principle as short selling by letting you borrow shares and pay them back when you settle your options contracts. But instead of shorting the stock, you're just buying/selling the right to short that stock -- and not shorting it -- just buying/selling the right. There's a difference. The amount you must pay (if you're a buyer) or the amount you collect (if you're a seller) for the right to short the stock is called the option premium. The idea is the same but less expensive because you use leverage to control huge position.

Buying "Put" Options

To buy a put option means that you're buying the right to short the stock (or buying the right to sell short the stock) by paying an option premium to the put seller. The keyword is selling short -- you're betting that the stock will fall below the strike price. So here, you need to distinguish the difference between plain 'selling short' the stock and 'selling put' options. There's a difference: in plain selling short you pay the full price of the stock whereas in options you only have to pay the premium price (also commonly called option premium) of the stock, because you're just buying the right to short the stock.

Selling "Put" Options

To sell a put option means that you're giving someone else the right to short the stock and collecting the option premium from the put buyer. Again, here you think that the stock is going to go up and you want to own that stock but you don't want to pay the full price of the stock; so you sell put options and collect option premium from the buyer. So selling put allows you to maximize your profits by reducing your upfront cost because you receive the option premium from the buyer. Selling put is a great strategy for long term investment--that is, if you want to own that stock that you think is going to go up long term wise.


Summary

An option gives you the right -- but not the obligation -- to buy or sell something. Buyers pay a non-refundable (deposit) called option premium amount to sellers in return for time to decide whether or not to conclude the deal. Sellers must be ready to sell [the subject] as soon as the buyers ready to buy at any time up to the expiration date.

The option contains a strike price, which is a set price you must pay when you decide to exercise your option at/or before a specific date in the future stated by the option contract.

Buyers and sellers can decide whether or not to go through with the deal any time up until the option's expriration date.

An expriration date is a date the option to be expired or ceased to exist. Only certain expriration dates are available. They're chosen by the exchange which lists the option.

In the meantime, the seller must always be ready to sell the stock or futures contract as soon as the buyer decides to buy. For this commitment, the seller receives money up front from the buyer called option premium.

Nearly all stock options are for 100 shares of a stock. Every futures option is for one futures contract (which represents a large quantity of a commodity; for example, for 1 corn futures contract contains 5,000 bushels of corn; for 1 crude oil contract contains 1,000 barrels of crude oil).

Remember that in options you can buy or sell calls or puts. Buying calls or puts will cost you money in the amount of premium you have to pay to the sellers, while selling calls or puts will earn you money from the premium you receive from the buyer.

There are at least 128 options strategies available for trading and each strategy is tailored to specific play. So these options strategies basically cover every possible market angles or outlooks or scenarios. You pick a certain strategy or combinations of strategies to play to fit your market outlook.

Options are great investment tools that let you delay buying or selling a stock or futures contract. They allow you to make large profits without having to tie up a lot of your own investment money.

Options Chain

The cost of of an option depends a lot on what's happening with the stock or futures contract involved. The more time there is until expiration, the larger the option premium you must pay the seller since the longer the time the more chance of a stock to go up in value.

Also, the greater the difference between the current stock price and the strike price, the greater the buyer's price (called option premium). For example:

Strike Symbol Last Chg % Bid Ask Volume Open Interest
$15.00 T100918C00015000 7.45 0.23 7.40 7.50 45 175
$25.00 T100918C00025000 3.45 0.04 3.40 3.50 106 694


XYZ stock is selling on the NYSE at $22 a share today:

  • Option 1 (ticker: T100918C00015000): Gives you the right to buy XYZ stock at $15 a share. option premium: $7.50 (the asking price. See the options chain above).

  • Option 2 (ticker: T100918C00025000): Gives you the right to buy XYZ stock at $25 a share. option premium: $3.50 (Ask column. See the options chain above).

Since you would rather have an option to pay $15 for a $22 stock instead of $25 for a $22 stock, option 1 is more valuable.

As a result, it costs more to buy option 1 than to buy option 2 ($7.50 for option 1 as appose to $3.50 for option 2).

To give you a better idea of what options price listing looks like, try Google a term "option chain AT & T" or put in any other company a stock symbol in the place of AT & T and you'll get an option chain for that company's stock.

A very good place to hang around is Yahoo Finance website where you can find a lot of stock and options information. On Yahoo Finance website, you can find options chains for any stock that has options. If you sign up for a free account, you can create portfolios and keep track of the stocks or options you're interested, even if you don't invest in them.

I, personally, have a free Yahoo Finance account where I basically create lots of portfolios, creating one portfolio for every stock I am interested in so that I can keep track of what that particular stock is doing. I have to admit, I have about 250 portfolios in my free Yahoo Finance account, with each portfolio containing one stock that I am watching and keeping track of it. I don't put more than one stock in any of my portfolio because the name of the portfolio tells me what kind of the stock I am watching for.

For example, I created a portfolio called: "Biotech AVEO 2.70 on 7-3-17" to remind me that this biotech stock was trading around $2.70 a share so that I know how I've done if I had bought it on that date. Most of the times, I name my fortfolio to be very long and very descriptive to reflect the catalyst of the stock so that I know what to expect. All of my "watch" portfolios have names identifying stock symbol, coverage stock price on date the coverage was made and some short description of the catalyst.

This way, months or years later, I can go back to see how my "fantasy" portfolios have done with its catalyst by just take a glance at the portfolio names and scan through the list of portfolios in a quick run through without wasting time going into each individual stock. It saves me tremendous time.

Sometimes, I name my fortfolio to be very long and very descriptive about its catalyst to remind me of certain events that might cause the stock to move dramatically, such as clinical trials are due to report or some court rulings are due in the future so that I can anticipate to play options on those events using advanced options strategies where I play options on stocks that are moving dramatically up or down.

I usually play directions and I don't care which direction the stock is moving as long as the stock is moving dramatically. This options play involves advanced strategies. I don't want to confuse beginners right now by explaining the strategies but maybe in the future tutorials I will lay them out.

Another very good website is called investing.com where you can signup for a free account and get access to all kinds of investing information, such as charts, technical and fundamental analysis, stocks screener, news alert on stocks, stock watch, etc.

In the option chain listing you'll see:

Strike Price, which is a set price you must pay when you decide to exercise your option at/or before a specific date in the future stated by the option contract.

Symbol is the unique symbol for that particular option. You need to copy this unique symbol and tell your broker that you want to buy this option.

Last is the closing price of the option premium -- last traded. This is the price traders paid for their options when a transaction was completed and reported. So last is the last price some buyers paid to buy their options last time (last traded transaction reported). You may or may not get to pay this price when you buy the options. You most often will have to pay the asking price. See Ask below.

Bid and Ask Principle

Before I go into the individual description of bid and ask, I want to give you an overview of the concept of these two principles. Have you ever watch auction proceedings? You know, the fast talking guy/gal (call the autioneer) who keeps repeating two prices (lower price and higher price) very fast over and over, and over, and over again in a thundering rhythm that no one seems to understand what the heck he/she is saying?

By the sheer thundering sound of it, it seems that the auctioneer is saying something special but in fact he/she actually just keeps repeating the bid and ask prices while mixing some of his/her own bravado in the mix, often saying the lower price first followed by the higher price next in a thundering rhythmic of sound that gets people to just get up and raise their hands to bid on the subject (or item).

All he/she does is just repeat that pattern over and over and over very fast and gets people excited to jump in and bid. So he/she starts with the starting price set by the seller first and then using that starting price as the bid price as if that price has already been bid. And then the autioneer just raises the bid price higher to make it as an ask price, and now the auctioneer has two prices to work with: bid price and ask price. Now the auctioneer just keeps repeating the two prices over and over, and over again until somebody raises his/her hand to bid on that item.

But the autioneer doesn't want to sell that item to the person that just bid just yet, so he/she keeps raising the ask price again, and this time to an even higher, and he/she repeats that same pattern again and again and again until somebody raises his/her hand again, and the autioneer again doesn't want to sell that item (not just yet), and he/she keeps repeating the same pattern until after a while he/she realizes that there aren't anymore bidders for that asking price, and finally, he/she awards the final bid to the last person who bid on that item.

So the key point to take away from the auction proceeding is that the auctioneer becomes the market maker who dictates how much prices to raise. Once the bidders bid on the item, that bid price becomes the lowest price given to that item, and the auctioneer, being the market maker, sets or raises the price higher to make the price as an asking price. And now the auctioneer has two prices to work with: bid price and asking price. So the auctioneer just repeats this pattern over and over and over.

In the financial world, the market maker (similarly to the auctioneer) sets prices higher or lower depending on the supply and demand. But the difference between the auctioneer and the market maker is that the auctioneer never move prices lower and lower if the demand is not met; whereas the market maker will move prices lower and lower and lower if the supply exceeds demand.

If you ever seen stock, bond, or commodity trading floors (also called pits) where a pit full of traders gathering around a group of market makers and shouting and signaling hands gestures to each other and to the market makers telling them how many shares/contracts, at what price to buy/sell. That was in the old days, but nowaday, trading is done electronically, usually from far distances and sometimes from all over the world.

The bid and ask pricing principle in the financial market follows the same auction pricing principle in which buyers bid to buy the items and sellers ask the buyers to buy the items. That is known as the bid-ask principle or bid-ask spread.

Note: The brokers who handle the buy/sell transactions get to keep the bid-ask spread prices and that's one of the ways brokers make money facilitating transactions to buyers and sellers. One important thing to note is that the higher the volume of a stock, the narrower the bid-ask spread. Although options tend to use volume as a mean to adjust the spreads as well, it uses other factors also in determning the spreads.

In stocks, thinly traded stocks have huge or wide spread -- meaning, if you trade a thinly traded stock you'll have to pay huge spread because the brokerages cannot make enough money if the spread is narrow and it is comparable to spreads in high volume stocks. Likewise, high volume stocks have narrow spreads because brokerages earn enough money with the high volume of transactions. For example, high volume multiply by narrow spread is signficant in money earn; whereas thinly traded stocks need wide spread to multiply with the low volume trades to make enough money comparable to high volume stocks. Brokerages are in the business of making money and making money off spreads is one way of doing that.

So, as an investor, there isn't any way of avoiding this loophole even if you have a brokerage service that charges no fee. They still earn their money through spread transactions automatically that they facilitate. Investors have to bite the bullit on this one.

Bid is the (last) price the buyer bid to buy that options. In the financial world, there are buyers and sellers and sellers set their prices by asking buyers to pay the asking price. Whereas buyers bid each other to buy the underline. So bid is the price some buyer(s) were willing to pay last time (last traded transaction). If you're a buyer, the bid price is the most likely price you'll have to pay for your options. However, since the listed bid price was the last price some buyers were willing to pay last time out, you may or may not get to buy/pay at that price.

In short, the bid price is the last bid price of the options premium that some buyers were willing to pay last time out or last transaction. This helps you gauge the market so that you can price your options accordingly. Again, if you're a buyer, you may or may not get to buy at this price when you buy your options. The bid/ask prices fluctuate according to the law of supply and demand.

Ask is the (last) price sellers were asking buyers to buy their options. Sellers set prices and buyers bid each other for the best price to buy. So ask is the price some sellers were asking buyers to buy this option last time (last traded transaction). Again, if you're a seller, you may or may not get to sell at this price when you sell your options. The bid/ask prices fluctuate according to the law of supply and demand. So in short, the ask price is the last price of the options premium some sellers were asking for buyers to buy last time out or last transaction. This helps you gauge the market so that you can price your options accordingly.

Vol is the total volume of that particular option traded on that day or up to the moment you view the listing. The Vol only lists the volume on that particular day up to the moment you view the listing. It's a daily volume or volume up to the moment you view the listing. The numbers represent the contracts -- total contracts. Use this number to gauge the current sentiment of the options.

Vol listing lists both buy and sell sides -- so there is no way of knowing how many contracts are long and how many contracts are short. It would be nice to know how many contracts are being bought to go long and how many contracts are being sold short. But at least we know how many contracts are being held in the option in both directions. You would need to go to the exchange's website to find out the individual side contracts. And yes, experienced traders do go to the exchange's website to find out this information so that they can make an informed decision.

Experienced traders usually glance through the daily volume for each option to see what kind of action an option receives. If all of a sudden, the volume spikes up unusually high, traders investigate on the option to see why that particular option receives a huge spike in volume. They may trade on that option to ride the co-tail of other traders who caused the volume to spike up. The higher the volume, the more interest the option attracts because traders like to follow one another's lead.

Open Interest is the total option contracts outstanding for that option. This is the accumulation of all the previously contract transactions up to now. Vol lists the total volume for the day up to the moment you view the chain, while open interest accumulates all the outstanding volumes by adding all previous volume up to the moment you view the chain. It's a total outstanding contracts of the option.

If the number is high it tells you that there is a lot of people are interested in holding this options. Use this number to gauge the sentiment of the option. The numbers represent the contracts -- total contracts outstanding.

Open Interest, again, lists both buy and sell sides -- so there is no way of knowing how many contracts are long and how many contracts are short, except by going to the exchange's website. It would be nice to know how many contracts are being bought to go long and how many contracts are being sold short. But at least we know how many (interested) contracts are being held in the option in both directions.

Here is what an options chain looks like:

Call Options Quotes
For AT & T, Inc (Symbol: T): 07-30-2010: $25.94
Expire at close on Friday September 17, 2010
Strike Symbol Last Chg % Bid Ask Volume Open Interest
$23.00 T100918C00023000 2.94 0.23 3.00 3.05 45 175
$24.00 T100918C00024000 2.15 0.04 2.10 2.13 106 694
$25.00 T100918C00025000 1.31 0.05 1.27 1.28 138 2,924
$26.00 T100918C00026000 0.63 0.00 0.60 0.61 322 11,331
$27.00 T100918C00024000 0.21 0.02 0.19 0.21 466 3,637
$28.00 T100918C00024000 0.06 0.01 0.04 0.06 120 808
$29.00 T100918C00029000 0.02 0.00 N/A 0.02 10 20
$30.00 T100918C00024000 2.15 0.04 2.10 2.13 106 694


Put Options Chain Quotes
For AT & T, Inc (Symbol: T): 07-30-2010: Price $25.94
Expire at close on Friday September 17, 2010
Strike Symbol Last Chg % Bid Ask Volume Open Interest
$23.00 T100918P00023000 0.05 0.00 0.09 0.11 6 1,651
$24.00 T100918P00024000 0.15 0.01 0.16 0.18 131 1,025
$25.00 T100918P00025000 0.31 0.00 0.32 0.34 76 3,194
$26.00 T100918P00026000 0.63 0.03 0.65 0.67 283 1,634
$27.00 T100918P00027000 1.24 0.02 1.24 1.27 273 1,774
$28.00 T100918P00028000 2.05 0.03 2.09 2.11 78 439
$29.00 T100918P00029000 3.15 0.15 3.05 3.10 89 18
$30.00 T100918P00030000 4.15 0.15 3.95 4.10 124 1


The OCC Symbology

When exchange traded options first came into popular existence in the 1970s, it was possible that the founders of the options industry neither fully realized just how useful and prevalent option trading would ultimately become, nor some of the changes that would occur in the ensuing decades. As such they set up a somewhat archaic and limiting method of designating option symbols for trading purposes. And the options symbols they used were not always uniformed nor easy to implement.

Then in the latter half of the first decade of the millenial (2000s), as options were becoming more popular and complex (such as using multi-legs strategies), the Options Clearing Corporation (OCC) began an initiative that set the stage for the implementation of a more intuitive and far more flexible method for designating option symbols. The intention of the OCC was for this new method to be uniformed and easy to use and to be fully in place by May of 2010.

Once completed the OCC distributed the guideline to the public world and now all options throughout the world use this OCC implementation.

The options symbol follows the OCC symbology pattern or format that is up to 21 characters that represents the contract specifications of a particular option. The following components are used in constructing the symbol:
Option Symbol Format

*(1) - Underlying symbol (IBM in this case, or in the previous options chain, T, for AT & T)
*(2) - 2 digit expiration year (14 for 2014)
*(3) - 2 digit expiration month (01 for January)
*(4) - 2 digit expiration day (18 for the 18th day)
*(5) - "C" for Call or "P" for Put
*(6) - 8 digit strike price (00200000 for $200.00).

In the options chain above: 00023000 ($23.00), 00024000 ($24.00), 00025000 ($25.00), 00026000 ($26.00), 00027000 ($27.00), 00028000 ($28.00), 00029000 ($29.00), 00030000 ($30.00).

Notice the strike price is represented in 8 digits no matter what the number of digits of the actual strike price. The strike price is carried to 3 decimal places, but no decimal is used within the symbol. For example, the $200 strike for the IBM option above is represented as "00200000".

Also, note the two "0's padded on the front to complete the 8 digit total. So the maximum strike price can be represent in this format of up to $99999.999 only -- a number unlikely to be surpassed in the options sphere.

Options Continue

The beauty of options is that your risk is limited to the option premium you pay to the seller. But your upside reward is limitless.

If you have the right to buy a stock at $20 a share and it's selling $22, $23, $24, or some other numbers, you could exercise your call option, pay $20 a share to the seller, then turn around and sell the shares on the open market at $22, $23, $24, or some other numbers that the market is offering.

Notice that in options you do not need to have a large sum of money to profit, even at the time of the exercise of the options. All you have to have is your options premium money for either puts or calls and you can buy the rights to puts or calls and when you decide to exercise your contracts the contracts are settled without you having to come up with extra money to cover the full price of the contracts. To better understand this, you'll have to actually get your hands-on-experience by trading options for a few times and you'll see exactly how it works.

Obviously, the higher the stock's price goes, the more you stand to profit. Sellers know this, so as the stock price rises and falls, the option price rises and falls with it.

Consequently, you can profit by just trading the rights to your option for more money than you paid -- without ever having to lay out the large sum needed to buy the 100 shares of stock or the futures contract.

Let's say you bought the stock outright at $22 a share and if that stock price fell from $22 to, say, $10 a share, you would have lost $12 a share just like that.

Now with options, your risk is only limited to the premium paid to the sellers. Take that same scenario above: had you bought a (call) option on that same stock, you would have lost only the premium paid to the seller, no matter how far the stock price fell.

As a result, when you buy an option, you know immediately the most you can lose. This is what the industry calls limited, predetermined risk.

Trading Technical Terms

What do the phrases "buy to open," "sell to open," "sell to close," and "buy to close" mean?

The confusing terminology mentioned in the question deals with entering and exiting option orders. There are two main ways in which you can participate in options: you can be either a buyer or a seller. Also, you must enter and exit the trades.



The above screen is a typical options order entry screen interface platform for entering orders. The various key items and their meanings are described below.

Option Symbol

The stock symbol or the specific option symbol you're trading.

Action

The action of entering or exiting the trade.

Quantity

The number of contracts you're buying or selling.

All or None

This feature is pertaining to the quantity just described above. This feature allows you to specify whether the order needs to be filled the entire order quantity or partial quantity. If you check this box when placing an order, your order will be filled only if there are enough contracts to be filled. If you leave it blank or unchecked, your order will be filled regardless of how many contracts available to be filled.

For example, if there are only 8 contracts available and you specified 10 contracts, your order will be filled for only 8 contracts and not the whole 10 contracts you had originally placed. On the other hand, if you check the box and there are only 8 contracts, your order is not filled -- you're not in the contract.

Price

The price specification is pertaining to the type of order as described below.

Types of Orders

Online brokerages provide many types of orders to cater to the various needs of the investors. The most common types of orders available are market orders, limit orders and stop orders. Some provide additional order types (as shown above): Market on Close (or commonly known as After-Hour Trading), Stop Limit, etc.

Market Order

With market orders, you are instructing your broker to buy or sell the options at the current market price. If you are buying, you will be paying the asking price. If selling, you will be selling at the bid price. The advantage of using market orders is that you will fill your order fast (often instantly) but the disadvantage is that you will usually end up paying slightly more, especially when the order is large and the trading volume thin.

Limit Order

With limit orders, you will specify the price you wish to transact. If you are buying, you are instructing your broker to buy at no higher than the specified price. If selling, you are telling him to sell at no less than your stated price. The advantage of using limit orders is that you are in full control of the price at which you buy or sell your options. The disadvantage is that filling the order will take some time, or the entire order may not get filled at all because the underlying stock price has moved way beyond your desired price.

Stop Loss Order

Stop loss orders are orders that only gets executed when the market price of the underlying stock reaches a specified price. They are used to reduce losses when the underlying asset price moves sharply against the investor.

Stop Market Order

A stop market order, or simply stop order, is a market order that only executes when the underlying stock price trades at or through a designated price. Buy stops, designed to limit losses on short positions, are placed above current market price. Sell stops are used to protect long positions and are placed below current market price.

While the stop market order guarantees execution, the actual transacted price maybe slightly lower or higher than desired, especially when the underlying price movement is very volatile.

Stop Limit Order

A stop limit order is a limit order that gets activated only when the underlying stock price trades at or through a specifed price. While a stop limit order provides complete control over the transaction price, it may not get executed if the underlying price moves too quickly and the limit price is never reached.

Duration

The duration specifies the length of time the order is to stay live or good. The two types of duration are:

Day Order

The day order specifies that the order is to stay open until the end of the trading day (of the day you place the order). At the end of the day, if the order is not filled, the order is no longer active and no order is carried forward to the next day to be filled. The order is voided. If you want your order to carry forward past the current day, you need to use a Good Til Cancel (or GTC) order.

Good Til Cancel (or GTC)

The GTC specifies that the order is good until you actually cancel it, regardless how many days, weeks, months or years it takes to fill the order.

Advanced Orders

Advanced orders are advanced types of orders typically available to sophisticated traders. Experienced traders use advanced orders to mitigate risk and to enter the market. These advanced orders include breakouts, retracements, MultiBrackets, Icebergs, market-on-close order (or MOC) which is a non-limit market order, and conditional orders like the one cancels other (also called order cancels order) order (OCO) and the order sends order (OSO).

Some interfaces classify trailing stop orders as advanced orders but trailing stop orders are available to beginners as well.

To Enter the Trade

When you enter a trade, you are essentially opening a position as either a buyer or a seller, hence the orders: "buy to open" (to enter a position as a buyer of call or put options) and "sell to open" (to enter a position as a seller of call or put options).

In other words, to buy a call or put options, you must put in a "buy to open" order. For examples, buy 2 (contracts) IBM 200 (strike) Call at $28.00 (premium) expired, say, in 2 months; buy 1 (contract) IBM 190 (strike) Put at $8.00 (premium) expired, say, in 3 months.

To sell a call or put options, you must put in a sell to open order. For examples, sell 2 (contracts) IBM 200 (strike) Call at $28.00 (premium) expired, say, in 2 months; sell 1 (contract) IBM 190 (strike) Put at $8.00 (premium) expired, say, in 2 months.

To Exit the Trade

Now, to exit a trade, you need to close your option position, whether that position is a long or short position. If you've bought a long option ("buy to open"), you need to use a "sell to close" order to exit the long position. On the other hand, if you've "sell to open" (wrote an option or had sold a short position), you will need to use a "buy to close" order to exit the short position.

While it may seem odd that you would buy to close a position, by taking a long position in the option that you shorted, you neutralize the position by buying a new option (go long) against the position you've wrote the option (earlier short position), and in effect closes your position. Confusing?

In summary, when you enter a trade, you are essentially opening a position as either a buyer or a seller. If you are buying an option, either a put or a call, you must enter a buy to open order. If you are writing an option (a seller), also referred to as selling an option, you must enter a sell to open order to sell either a call or put options.

Yes, these terms can be confusing if you're not practicing it regularly.

What does "In the Money" means?

In the money means that your stock option is worth money and you can turn around and sell or exercise it. For example, if John buys a call option on ABC stock with a strike price of $12, and the price of the stock is sitting at $15, the option is considered to be in the money.

What do "In the Money Call, In the Money Put Option, Deep in the Money " mean?

Definition of "In the Money Call":

A call option is said to be in the money when the current market price of the stock is above the strike price of the call. It is "in the money" because the holder of the call has the right to buy the stock below its current market price. When you have the right to buy anything below the current market price, then that right has value. That value is also referred to as the option's "intrinsic value." That value is equal to at least the amount that your purchase price (strike price) is below the market price. In the world of call options, your call options are "in the money" when the strike price of your calls are less than the current market price of the stock. The amount that your call options' strike price is below the current stock price is called its "intrinsic value" because you know it is worth at least that amount. This compares to an out of the money call option which is call option where the strike price of the call is above the stock's current market price.

Definition of "In the Money Put":

A put option is said to be in the money when the strike price of the put is above the current price of the underlying stock. It is "in the money" because the holder of this put has the right to sell the stock above its current market price. When you have the right to sell anything above its current market price, then that right has value. That "intrinsic value" is equal to at least the amount that your strike price is above the market price. In the world of put options, your put option is "in the money" when the strike price of your put is above the current market price of the stock. The amount that your put option's strike price is above the current stock price is called its "intrinsic value" because you know it is worth at least that amount.

Definition of Deep in the Money:

An option (Call or Put) is said to be "deep in the money" if it is in the money by more than $10. This phrase applies to both calls and puts. So, "deep in the money" call options would be calls where the strike price is at least $10 less than the price of the underlying stock. Put options would be "deep in the money" if the strike price is at least $10 higher than the price of the underlying stock.

Example of Deep in the Money Calls and Puts:

Suppose YHOO is at $40 and you think YHOO's stock price is going to go up to $50 in the next few weeks. If you bought the YHOO $40 calls and then in the next few days you find out you were right and YHOO is at $52, then your $40 calls are in the money $12 and they would be considered deep in the money call options.

Likewise if you had a YHOO $55 put, then this put would be considered deep in the money when YHOO is at $40, but once YHOO climbed to $52, it is still in the money, but it would not be considered deep in the money.

The advantage of buying deep in the money calls and puts is that their prices tend to move $1 for $1 with the movement of the underlying stock. So, if you are absolutely certain that the price of the underlying stock is going to move a lot and move quickly, then you will earn a higher percentage return trading these calls and puts than trading the stock itself.

Calls and Puts Trading Tip:

Why is this distinction between ITM calls and puts and a DEEP ITM calls and puts? The first thing to understand is that options with strike prices near the price of the underlying stock tend to have the highest risk premium or time-value built into the option price. This is compared to deep in the money options that have very little risk premium or time-value built into the option price.

For example, if YHOO is at $40, the current month $40 call might be priced at $1.50. That $40 call is ATM so its intrinsic value is $0 (meaning that there isn't an actual gain in cash value for you to cash out your position to gain a profit) but traders are willing to bet $1.50 that the price of YHOO will move up to and higher than $41.50 which is the breakeven point. The YHOO $30 call however, might be price at $10.25. The $30 call is obviously ITM $10 so the risk premium or time-value is only $0.50.

You will often hear traders talk about Time Value a lot. Time Value means nothing more than the Premium Price you pay or receive (as a buyer or seller). See an extensive explanation later.

What do "Out of the Money Call, Out of the Money Put Option and At the Money Option" mean?

Definition of "Out of the money" and "out-of-the-money":

A call option is said to be out of the money if the current price of the underlying stock is below the strike price of the option.

A put option is said to be out of the money if the current price of the underlying stock is above the strike price of the option.

Example of an "Out of the Money CALL Option":

If the price of YHOO stock is at $37.50, then all of the call options with strike prices at $38 and above are out of the money.

Why are they out of the money? They are out of the money because those options don't have any intrinsic value. If you have the right to buy YHOO at $40 and the current market price is $37.50, then that YHOO $40 call is out of the money by $2.50. If you had that call and you had to exercise it, you could buy shares of YHOO at $40 and sell them immediately in the open market for $37.50 for a loss of $2.50. Would you do that? Absolutely not! So they are out of the money.

Likewise the YHOO $45 and $50 calls are also way out of the money.

If YHOO is at $37.50, then all of the call options with a strike price of $37 and below are in the money.

Example of an "Out of the Money PUT:

If the price of MSFT stock is at $37.50, then all of the put options with strike prices at $37 and below are out of the money.

Why are they out of the money? They are out of the money because those options don't have any intrinisc value. If you have the right to sell MSFT at $35 and the current market price is $37.50, then that MSFT $40 put is out of the money by $2.50. If you had that put and you had to exercise it, you could sell shares of YHOO at $35 and buy them immediately in the open market for $37.50 for a loss of $2.50. That doesn't make sense so they are out of the money.

Likewise the MSFT $30 put is out of the money by $7.50 and the MSFT $25 put is out of the money by $12.50.

If MSFT is at $37.50, then all of the put options with a strike price of $38 and higher are in the money.

Definition of "At The Money" Option:

An option is said to be at the money if the current stock price is equal to the strike price. It doesn't matter if we are talking about calls or puts. Any call or put whose underlying stock price equals the strike price is said to be at the money. Sometimes you will see "At The Money" abbreviated as "ATM." You may also see "OTM" which mean "Out of the Money" and ITM which means "In the Money".

Moneyness

Moneyness is a term describing the relationship between the strike price of an option and the current trading price of its underlying security. In options trading, terms such as in-the-money, out-of-the-money and at-the-money describe the moneyness of options. The price movement of the options.

Instrinsic Value

The two components of an option premium are the intrinsic value and time value of the option. So instrinsic value is a term describing the option's actual value that can be cashed out. By definition, the only options that have intrinsic value (that can be cashed out) are those that are in-the-money. For calls, in-the-money refers to options where the strike price is less than the current underlying price. For example, a call option with a strike price of $25 in premium of $3 and the current price of the stock is $27 causing this option to have an intrinsic value of $2 ($27 - $25).

If you own this option you can cash out your position because it is an in-the-money option and has intrinsic value. In other words, an intrinsic value is an option that has real value to you--it is worth something to you. In this case, it is worth $2 per share to you; however, even though this option has instrinsic value it is not a profitable option, because its premium ($3 per share) is higher than its intrinsic value ($2 per share). So you still end up a $1 per share loss if you cash out right now. So your hope now is to depend on time value to save you the day. See time value next.

Time Value

The two components of an option premium are the intrinsic value and time value of the option. Time value is a term describing the value of the option in relationship between the length of time of an option to expiration and the current trading price of its underlying security. The more time to expiration, the greater the time value of the option. Think of an option that has no intrinsic value right now but give it time and that option might be worth something (and have intrinsic value). This is called time value -- time is all that option has right now because it doesn't have intrinsic value -- it cannot be cashed out right now, so it has time to expiration to make this option worth something. The time between now and the expiration is called time value. As the expiration date gets closer and closer the time value decreases smaller and smaller and eventually the option is worthless if the stock price doesn't move in the direction of your option.

One indicator that represents the time value is the option price or premium on the contract. So when traders talk about time value, they really mean the actual premium price. If you look at the options premium on any particular option, it gets smaller and smaller in prices as the expiration date approaches. This is called time value.

Time value represents the amount of time the option position has to become profitable due to a favorable move (a move in the desired direction of your option) in the underlying price. In most cases, investors are willing to pay a higher premium for more time (assuming the different options have the same exercise price), since time increases the likelihood that the position will become profitable. In other words, a lot of options traders are willing to choose longer expiration dates to give their options long enough time to move in their desired direction. In general, the longer the time of expiration date the more chances stocks or options move or fluctuate. So time is precious in options trading because the lesser time to expiration the more chances that your option is becoming worthless.

Managing Time or Trades

Now that you know what instrinsic value and time value are and how they work, it's time to learn how to manage your trades. Managing your options trades is not a requirement for most beginners, but experienced active daytraders usually always manage their trades regardless the trades go their way or not.

Why do experienced traders manage their trades?

A simple answer is: maximize profits and minimize losses.

One of the tools they use is the stop loss and trailing stop. See my tutorials on the topics.

Suppose that you place a trade and you expect the stock/options to move in the direction you desire but after a while the position is going against you and the expiration date is fast approaching and you realize that there is no way you're going to make money on your contract. Here is my advice: cut your losses -- the sooner you realize the position is not going to turn good, the better off you are, and the sooner you cut your losses is the better off you are.

Do not try to hope for the best -- the best will never materialize if the trend is going against you. So cutting your losses is the best way to manage your trades. If the trend is going against you: cut your losses -- and don't hope for a miracle! Get out as soon as possible. There are plenty of opportunities to make money else where, and don't falling in love and marry to your positions.

You can cut your losses even if your options are not in the money as long as the options have intrinsic value. To illustrate this, I'm going to use my actual trades I've made, in which, I anticipated the stocks to move dramatically because of Phase III report was dued to report, but after the report the stock didn't move a needle and I realized afterward that there isn't any catalyst to look forward to, to move the stock higher, so I decided to get out and use the remaining proceeds to play other trades. Here are the positions that I've cut my losses:


If you look at the time value, I still have plenty of time value to be had and the options could turn out to be profitable, but I decided that if the Phase III reports didn't move the stock/options then what else will? So I'm not going to hope for the best! To save space, here is one of the positions that I've got out:


Black Scholes Option Pricing Model


Definition of the Option Pricing Model Using the Black Scholes:

The Option Pricing Model is a formula that is used to determine a fair price for a call or put option based on factors such as underlying stock volatility, days to expiration, and others. The calculation is generally accepted and used on Wall Street and by option traders and has stood the test of time since its publication in 1973. It was the first formula that became popular and almost universally accepted by the option traders to determine what the theoretical price of an option should be based on a handful of variables.

Here is a break down of the formula above. DO NOT be frightened by the scary look of the formula because it is for demonstration purpose only and you do not need to understand any of these mathematical properties.





Note that risk-free interest rate means the interest rate is constant throughout the period in the timeframe or expiration period. In another word, it's a fixed interest rate that stays constant throughout the expiration period.

So options trading terms can be confusing initially but once you practice it in real life you'll understand better quickly. You need to be familar with these terms just described and one more key factor in options trading, which is called implied volatility. In options trading, implied volatility is probably the most important key factor that seperates a successful trader from an unsuccessful trader.

Understanding the concept of implied volatility and learning how to use it is key to become a successful options trader. The following describes the concept of implied volatility:

Implied Volatility

What is Implied Volatility?

Implied volatility (IV) is one of the most important concepts for options traders to understand for two reasons. First, it shows how volatile the market might be in the future. Second, implied volatility can help you calculate probability. This is a critical component of options trading which may be helpful when trying to determine the likelihood of a stock reaching a specific price by a certain time.

Keep in mind that while these reasons may assist you when making trading decisions, implied volatility does not provide a forecast with respect to market direction. Although implied volatility is viewed as an important piece of information, above all it is determined by using an option pricing model, which makes the data theoretical in nature. There is no guarantee these forecasts will be correct.

Understanding IV means you can enter an options trade knowing the market's opinion each time. Too many traders incorrectly try to use IV to find bargains or over-inflated values, assuming IV is too high or too low. This interpretation overlooks an important point, however.

Options trade at certain levels of implied volatility because of current market activity. In other words, market activity can help explain why an option is priced in a certain manner. Here we'll show you how to use implied volatility to improve your trading. Specifically, we'll define implied volatility, explain its relationship to probability, and demonstrate how it measures the odds of a successful trade.

Historical vs. implied volatility

There are many different types of volatility, but options traders tend to focus on historical and implied volatilities. Historical volatility is the annualized standard deviation of past stock price movements. It measures the daily price changes in the stock over the past year.

In contrast, IV is derived from an option's price and shows what the market "implies" about the stock's volatility in the future. Implied volatility is one of six inputs used in an options pricing model shown in the Black Scholes Pricing formula shown earlier, but it's the only one that is not directly observable in the market itself. IV can only be determined by knowing the other five variables and solving for it using a model. Implied volatility acts as a critical surrogate for option value -- the higher the IV, the higher the option premium.

Since most option trading volume usually occurs in at-the-money (ATM) options, these are the contracts generally used to calculate IV. Once we know the price of the ATM options, we can use an options pricing model and a little algebra to solve for the implied volatility.

Some question this method, debating whether the chicken or the egg comes first. However, when you understand the way the most heavily traded options (the ATM strikes) tend to be priced, you can readily see the validity of this approach. If the options are liquid then the model does not usually determine the prices of the ATM options; instead, supply and demand become the driving forces.

Any times market makers will stop using a model because its values cannot keep up with the changes in these forces fast enough. When asked, "What is your market for this option?" the market maker may reply "What are you willing to pay?" This means all the transactions in these heavily traded options are what is setting the option's price. Starting from this real-world pricing action, then, we can derive the implied volatility using an options pricing model. Hence it is not the market markers setting the price or implied volatility; it's actual order flow.

Implied volatility as a trading tool

Implied volatility shows the market's opinion of the stock's potential moves, but it doesn't forecast direction. If the implied volatility is high, the market thinks the stock has potential for large price swings in either direction, just as low IV implies the stock will not move as much by option expiration.

To option traders, implied volatility is more important than historical volatility because IV factors in all market expectations. If, for example, the company plans to announce earnings or expects a major court ruling, these events will affect the implied volatility of options that expire that same month. Implied volatility helps you gauge how much of an impact news may have on the underlying stock.

How can option traders use IV to make more informed trading decisions? Implied volatility offers an objective way to test forecasts and identify entry and exit points. With an option's IV, you can calculate an expected range -- the high and low of the stock by expiration. Implied volatility tells you whether the market agrees with your outlook, which helps you measure a trade's risk and potential reward.

Defining standard deviation

First, let's define standard deviation and how it relates to implied volatility. Then we'll discuss how standard deviation can help set future expectations of a stock's potential high and low prices -- values that can help you make more informed trading decisions.

To understand how implied volatility can be useful, you first have to understand the biggest assumption made by people who build pricing models: the statistical distribution of prices. There are two main types which are used, normal distribution or lognormal distribution.

The image below is of normal distribution, sometimes known as the bell-curve due to its appearance. Plainly stated, normal distribution gives equal chance of prices occurring either above or below the mean (which is shown here as $50). We are going to use normal distribution for simplicity's sake. However, it is more common for market participants to use the lognormal variety.

Why, you ask? If we consider a stock at a price of $50, you could argue there is equal chance that the stock may increase or decrease in the future. However, the stock can only decrease to zero, whereas it can increase far above $100. Statistically speaking, then, there are more possible outcomes to the upside than the downside. Most standard investment vehicles work this way, which is why market participants tend to use lognormal distributions within their pricing models.

With that in mind, let's get back to the bell-shaped curve (see Figure 1). A normal distribution of data means most numbers in a data set are close to the average, or mean value, and relatively few examples are at either extreme. In layman's terms, stocks trade near the current price and rarely make an extreme move. Figure 1 (below):


Let's assume a stock trades at $50 with an implied volatility of 20% for the at-the-money (ATM) options. The implied volatility is a proxy for standard deviation in percentages and are calculated and given in the options chain. If you look in the options chain of any stock, you'll see implied volatility percentages for each option. So when you need to do some calculations like we're doing right now, you can just take it from the options chain and use in your calculations (in this example, we make up the 20% for illustration purpose). That is if you're doing by hand; however, if you're using Trade King's calculator (illustrated below) the implied volatility percentage and other items inputs are entered automatically by the tool, making your calculations much, much easier.

Statistically, IV is a proxy for standard deviation. In other words, IV is a representation of the standard deviation. It acts like standard deviation moves--it acts as a proxy signal. If we assume a normal distribution of prices, we can calculate a one standard-deviation move for a stock by multiplying the stock's price by the implied volatility of the at-the-money options:

One standard deviation move = $50 x 20% = $10

The first standard deviation is $10 above and below the stock's current price, which means its normal expected range is between $40 and $60. Standard statistical formulas imply the stock will stay within this range 68% of the time (see Figure 1).

All volatilities are quoted on an annualized basis (unless stated otherwise), which means the market thinks the stock would most likely neither be below $40 or above $60 at the end of one year. Statistics also tell us the stock would remain between $30 and $70 -- two standard deviations -- 95% of the time.

Furthermore it would trade between $20 and $80 -- three standard deviations -- 99% of the time. Another way to state this is there is a 5% chance that the stock price would be outside of the ranges for the second standard deviation and only a 1% chance of the same for the third standard deviation.

Keep in mind these numbers all pertain to a theoretical world. In actuality, there are occasions where a stock moves outside of the ranges set by the third standard deviation, and they may seem to happen more often than you would think. Does this mean standard deviation is not a valid tool to use while trading? Not necessarily. As with any model, if garbage goes in, garbage comes out.

If you use incorrect implied volatility in your calculation, the results could appear as if a move beyond a third standard deviation is common, when statistics tell us it's usually not. With that disclaimer aside, knowing the potential move of a stock which is implied by the option's price is an important piece of information for all option traders.

Standard deviation for specific time periods

Since we don't always trade one-year options contracts, we must break down the first standard deviation range so that it can fit our desired time period (e.g. days left until expiration). The formula is: Figure 2 (below)


Note: it's usually considered more accurate to use the number of trading days until expiration instead of calendar days. Therefore, remember to use 252 -- the total number of trading days in a year.

As a short cut and a clever way to simplify the math, many traders will use 16, since it is a whole number when solving for the square root of 256 [16 X 16 = 256].

How would you like to solve the square root of 252?. But there are only 252 trading days in a year, so we'll have to find 4 extra days to trade -- maybe on four saturdays every year. 252 + 4 = 256.

Let's forget about the yearly precision talk above and assume that we are dealing with a 30 calendar-day option contract, which is very precised and very common for everyday trades. The first standard deviation would be calculated as: Figure 3 (below)


In this example, we use 10% for IV instead of 20% as shown earlier. For real life trades, you can use whatever % IV shown in the option chain on the option you're trading.

A result of (+/-)1.43 means the stock is expected to finish between $48.57 and $51.43 after 30 days (50 +/- 1.43). [+/- means plus or minus. So (+/-)1.43 means +1.43 or -1.43; 50 +/- 1.43 means 50 + 1.43 or 50 - 1.43].

Figure 4 (below) displays the results for 30, 60 and 90 calendar-day periods. The longer the time period, the increased potential for wider stock price swings. Remember implied volatility of 10% will be annualized, so you must always calculate the IV for the desired time period.


Does crunching numbers make you nervous? No worries, TradeKing has a web-based Probability Calculator that will do the math for you, and it's more accurate than the quick and simple math used here.

[A side note: TradeKing was bought by Ally Financials in 2015 and no longer operating a brokerage trading business as of the end of 2015. So if you're looking to find the TradeKing's web-based Probability Calculator and other trading tools mentioned in this article, you can signup a trading account at Ally Financials and they should have integrated all TradeKing trading tools into their own trading platform.]

Now let's apply these basic concepts to two examples using fictitious stock XYZ.

A stock's "probable" trading range

Everyone wishes they knew where their stock may trade in the near future. No trader knows with certainty if a stock is going up or down. While we cannot determine direction, we can estimate a stock's trading range over a certain period of time with some measure of accuracy. The following example, using TradeKing's Probability Calculator, takes options prices and their IVs to calculate standard deviation between now and expiration, 31 days away. (see Figure 5 below)


This tool uses five of the six inputs of an options pricing model (stock price, days until expiration, implied volatility, risk-free interest rate, and dividends) using a lognormal distribution to calculate the standard deviations. Note that risk-free interest rate means the interest rate is constant throughout the period in the timeframe or expiration period. In another word, it's a fixed interest rate.

Why throw in interest rate and dividend into the calculation of the price of a stock?

Well, if you're going to calculate the true future stock price to be as close to the actual future price as possible you would have to account for all of the factors that effect a stock price. Interest rate does effect a stock price because of inflation. Stock prices use money as its denomination and money inflates based on the rate of inflation and interest rate is a proxy of inflation.

Likewise, dividends effect a stock price as well. If you buy a stock at $10 a share today that pays an annual dividend of $1 a share, your stock price should be worth $11 a share after one year [not accounting for other factors such as business condition], $12 a share after two years, $13 a share after three years, and so forth. You only have to spend $10 to earn those amounts [$11, $12, $13,...] including dividends, so the true, actual stock price should at least be at those amounts after those years. So the future stock price calculation should account for the dividends as well.

Notice that the normal distribution shown in the early examples doesn't use five inputs as this one does. The lognormal distribution uses all the inputs contain in the normal distribution plus two additional inputs: risk-free interest rate and dividends. This is more accurate than the normal distribution calculation because it accounts for interest rate and dividend.

Once you enter the stock symbol and the expiration (31 days), the calculator inserts the current stock price ($104.91), the at-the-money implied volatility (24.38%), the risk-free interest rate (.3163%), and the dividend (55 cents paid quarterly). Notice that using the tool simplifies the entering of inputs greatly -- you only have to enter two items: stock symbol and the expiration date.

Let's start with the bottom of the screenshot above. The different standard deviations are displayed here using a lognormal distribution (first, second and third moves). There is a 68% chance XYZ will between $97.49 and $112.38, a 95% chance it will be between $90.81 and $120.66, and a 99% chance it will be between $84.58 and $129.54 on the expiration date.

XYZ's first standard deviation limits can then be inputted at the top right of the calculator as the First and Second Target Prices. After you hit the Calculate button, the Probability of Touching will display for each price. These statistics show the odds of the stock hitting (or touching) the targets at any point before expiration. You'll notice the Probabilities at the Future Date are also given. These are the chances of XYZ finishing above, between, or below the targets on the future date expiration).

As you can see, the probabilities displayed show XYZ is more likely to finish between $97.49 and $112.38(68.28%) than above the highest target price of $112.38 (15.87%) or below the lowest target price of $97.49 (15.85%). There is a slightly better chance (.02%) of reaching the upside target, because this model uses a lognormal distribution as opposed to the basic normal distribution found in Figure 1.

When examining the probability of touching, you'll notice XYZ has a 33.32% chance of climbing to $112.38 and a 30.21% chance of falling to $97.49. The probability of it touching the target points is about double the probability of it finishing outside this range at the future date.

Using TradeKing's Probability Calculator to help analyze a trade

Let's put these theories into action and analyze a short call spread. This is a two-legged trade where one leg is bought (long) and one leg is sold (short) simultaneously. Bear in mind, because this is a multiple-leg option strategy it involves additional risks, multiple commissions, and may result in complex tax treatments. Be sure to consult with a tax professional before entering this position.

When using out-of-the-money (OTM) strikes, the short call spread has a neutral to bearish outlook, because this strategy profits if the stock trades sideways or drops. To create this spread, sell an OTM call (lower strike) and buy a further OTM call (higher strike) in the same expiration month. Using our earlier example, with XYZ trading at $104.91, a short call spread might be constructed as follows:

* Sell one XYZ 31-day 110 Call at $1.50        (this means selling one Call option contract with a strike price of $110 at premium price of $1.50 and will expires in 31 days)

* Buy one XYZ 31-day 115 Call at $0.40        (this means buying one Call option contract with a strike price of $115 at premium price of $0.40 and will expires in 31 days)

Total credit = $1.10 ($1.50 - $0.40)

Remember that in options you can buy or sell calls or puts, and here we're buying one call contract and sell one call contract. This is called a bear call spread because this strategy profits if the stock trades sideways or drops.

Check out the tutorials on options spreads: Option Spread Strategies. Buying calls or puts will cost you money in the amount of premium you have to pay, while selling calls or puts will earn you money from the premium you receive from the buyers.

In multple legs strategies, experienced traders use the buys and sells combination to increase odds of profitability while minimize risk and at the same time can lower investment cost by balancing debit and credit combinations. As you can see in the above example, you receive more credit than the debit that you have to pay.

Another name for this strategy is the call credit spread, since the call you're selling (the short option) has a higher premium than the call you're buying (the long option). The credit is the maximum profit for this spread ($1.10). The maximum loss or risk is limited to the difference between the strikes less the credit (115 - 110 - $1.10 = $3.90).

The spread's break-even point at expiration (31 days) is $111.10 (the lower strike plus the credit: 110 + $1.10). Your goal is to keep as much of the credit as possible. In order for that to happen, the stock must be below the lower strike at expiration. As you can see, the success of this trade largely boils down to how well you choose your strike prices.

No worries, we have the Probability Calculator to help analyze the above strikes, let's use TradeKing's Probability Calculator. No guarantees are given by using this tool, but the data it provides may be helpful.

In Figure 6 (below), all the inputs are the same as before, with the exception of the target prices on the right side of the screen.

To start, you'll have to calculate the spread's break-even point ($111.10) and the maximum loss ($3.90), which we've already done so above.

Next, you enter the target prices on the right side of the screen. Every thing else stays the same. The spread's break-even point ($111.10) is the first target price (upper right). Its largest loss ($3.90) occurs if XYZ finishes at expiration above the upper strike ($115 = $111.10 + $3.90) by expiration -- the second target price.

That's all you have to enter. After you entered all information and click a button "Calculate" the screen like figure 6 below is shown.


Based on an implied volatility of 24.38%, the Probabilities at the Future Date indicate the spread has an 80.10% chance of finishing below the lowest target price (111.10). This is our goal in order to retain at least one cent of the $1.10 credit.

The odds of XYZ finishing between the break-even point and the higher strike (111.10 and 115) is 10.81%, while the probability of XYZ finishing at 115 (or above) -- the point of the spread's maximum loss -- is 9.09%. To summarize, the chances of having a one-cent profit or more are 80.10% and the odds of having a one-cent loss or more are 19.90% (10.81% + 9.90%).

Although the spread's probability of a gain at expiration is 80.10%, there is still a 41.59% chance XYZ will touch its break-even point ($111.10) sometime before 31 days have passed. This means based on what the marketplace is implying the volatility will be in the future, the short call spread has a relatively high probability of success (80.10%). However, it's also likely (41.59% chance) this trade will be a loser (trading at a loss to the account) at some point in the next 31 days.

Many credit spread traders exit when the break-even point is hit. But this example shows patience may pay off if you construct spreads with similar probabilities. Don't take this as a recommendation on how to trade short spreads, but hopefully it's an instructive take on the probabilities that you may never have calculated before.

If the discussion of implied volatility and the examples shown thus far make your head dizzy, there is an alternative simple way to by-pass all that crazy mathematic and its computation by having others doing all that crazy stuffs for you so that you don't have to worry about any of the crazy computation.

In the near distance future, I will offer a subscription membership for those of you who want to earn more money using the "crazy" computation just discussed here along with many more advanced strategies. My advanced strategies offer you multitudes of opportunities for aggressive investors to earn high returns in a short amount of time; and of course using safe and sound strategies.

I will do all the research plus doing all that crazy math for you and come up with a playbook that spells out exactly what to do in a clear and concise manner so that even a novice beginner in options can follow and understand. If you can understand the credit spread example shown earlier you'll definitely understand my "serve in a plate" playbook instructions.

You don't need to do research to come up with what stocks to play and you certainly don't need to come up with what option price targets to trade; I'll do it all for you and give you a "serve in a plate" playbook instruction, saving you time and headaches. Please stay tuned!!!

In conclusion ....

Hopefully by now you have a better feel for how useful implied volatility can be in your options trading. Not only does IV give you a sense for how volatile the market may be in the future, it can also help you determine the likelihood of a stock reaching a specific price by a certain time. That can be crucial information when you're choosing specific options contracts to trade. So understanding the concept of implied volatility and learning how to use it is key to become a successful options trader.

Good Luck Trading!!!


A Trading Strategy: Selling "Put" Options

Wouldn't it be great if there was a way to buy stocks at below market prices?

And yes, there is, and here's a strategy of buying stocks at discount to the market.

There's an investment strategy that can help you get stocks at the price you want to pay. What's more, this strategy can also put money in your pocket immediately.

I'll tell you all about it in a second, but first, a little background.

The strategy involves using options to buy stock. It's not widely used by the average investor, but it should be. The problem is most people think options are too complicated.

But I'm going to change that, at least for this exciting options strategy. And soon you'll never have to pay full price for a stock again!

The strategy I'm talking about is: selling put options.

Here are some of the basics to get started:

First, you've got to do your research and find a stock you want to buy. It should be a stock that you wouldn't mind owning even if the price drops significantly. Blue Chip stocks are usually good for this strategy. Stocks that pay dividends even better if you want some income to go along with the equity. But it doesn't have to be stocks with dividends--any stable stocks are fine. This is a long term investment strategy and we don't have to worry about the market volatility.

Examples of blue chip stocks are Walmart, Mcdonalds, Google, Apple, Facebook, Microsoft, Intel (INTC), 3M, AbbVie, Merck, Johnson & Johnson, Bristol Meyer, Exon Mobil, Chevron, Hess, Bank of America, Citygroup, Goldman Sach, Yum! Brands, Pepsi, Coca Cola, GM, Ford, etc. If you don't like the list that I mention here, there are thousands of blue chip stocks out there that you can choose from. You don't have to choose from the list here. You can find your own blue chip stocks that fit your personal preference.

Once you have the stock, you'll need to figure out what price you're willing to pay for it, preferably a price below the current market price. Don't be afraid to choose a price that's 10% or even 15% below the stock's current market price.

Next, you're going to need to pick a timeframe for the trade.

Remember, every option contract has an expiration date. Any time prior to expiration, your put option can be exercised by the buyer. If that happens, you'll have to buy 100 shares immediately.

Let's be clear, when you sell a put option, you don't have any say when you'll have to buy your shares. Only the buyer of the put option has that choice. The seller must buy the shares as soon as the option buyer exercises the put. So, make sure you always have enough money in your account to buy the 100 shares. I'm using one contract for this example, which is 100 shares. In your case, you can trade as many contracts as you wish. Just remember to do your math to come up with the required money for the transactions.

Getting back to the timeframes! I like to use four months to a year. I've found these time periods usually offer the best risk/reward profile. And more importantly, they tend to offer the highest option premiums. Of course, you don't have to stick to the timeframe I'm using. You can use any timeframe you like and it won't hurt you at all. Four months is just an example, in your case, you can use any length in expiration, say, one month, two months, or even in weeks, say, two weeks, three weeks or weekly since they now have weekly options.

Ok, now you've got your stock, the timeframe for the trade, and the price you're willing to pay.

Sounds good! Let's see how the strategy works!

To make this easier to understand, I'm going to use a real world example. Let's say you want to buy shares of Exxon Mobil (XOM). Right now (March 15, 2018) the stock is trading around $74 or $75 a share. But you decided that $65 is the most you feel comfortable paying over the next four months. That is roughly a 13% discount.

Here's how you make your trade:

  • First, sell one October 19, 2018 put option with a strike price of $67.50 for $2.50 a share in premium. Since each put contract controls 100 shares, you'll be collecting $250 (100 x $2.50). Your account will show you've sold one put contract and immediately your cash balance is higher by $250.

    For some investors, this is called naked put, which doesn't require you to have enough money to pay for the total price of the stock because their broker allows them to buy on margin. This is for people who have some experience trading options. However, for this tutorial, I am aiming for the non-experience options traders, i.e., long term investors who don't trade options for a living.

    So in your case, you would buy a cash-secured put, which requires you to have enough money in your account to cover the transaction. No big deal! Because your intention is to invest for the long haul and part of investing for the long term is to come up with the money to buy the stock outright. But in this case, you're not buying the stock outright -- well, not at the moment of your trading. Eventually, you'll have to buy the stock outright when the buyer of your cash-secured put decides to exercise his/her option from you. That's why you have to have enough money in your account to trade this option.

  • A typical stocks/options order entry screen interface platform for entering orders looks something like this:



    Notice that the various key items in the screen interface maybe arranged in different order and location for different brokerage services interface, but all the items should be there.

  • In technical term, you would in your brokerage account web interface select the type of trades you want to trade: stocks or options. In this case, you want to trade options and you select 'options' from the panel and the interface displays the options pane for you to trade.

    Next, select the symbol of the stock (XOM), select the expiration date (October 19, 2018), select the type of trade (in this case, a "Put"), select the "Sell to Open" (you're opening a position as a seller to sell the option), select the quantity of the option [1 for one contract], select the strike price (in this case $67.50) of the option you want to sell and immediately the premium for that strike price is automatically calculated by the brokerage system and appeared instantly (in this case $2.50).

    Next, click on "Preview" to see your order and if it's what you entered, click "Send" or "Order," depending your interface.

    Congratulation! Now you're an expert on how to trade options -- well, a put option.

  • And that is it! Very simple!

    This is called cash-secured put or covered put -- you're securing the trade with your money deposited in your account ready to buy the stock as soon as the buyer of your put option decides to excerise the option.

    Meanwhile, you don't have to do anything but only wait for the expiration date to arrive. You can also work on your next cash-secured put trade because at any time from now until expiration, your outstanding cash-secured put option may get exercised. Once it does, you can pull the trigger on your next trade.

  • As of now, your trade is on, now you just need to wait for Exxon Mobil's stock to approach $67.50.

    But hold on, as expiration approaches, some interesting scenarios can play out.

    If October expiration passes and Exxon Mobil's is still trading at around $75 a share, you're sitting pretty. The put option you sold expires worthless (to the buyer) and you get to keep the $250 premium as pure profit. That's a 4% yield on the cash you were holding to buy the stock (which is $6750 = 100 x $67.50.) Again, you have to have at least $6750 in your account. In addition, if you did this every four months, that would be a 12% annual yield.

    Let's face it... you're certainly not going to earn 12% interest from your bank right now.


  • Now you can sell another put option on Exxon Mobil's and collect more premium. And you can continue to capitalize as long as your put options keep expiring worthless.

If you're paying attention, I chose October 19, 2018 as the expiration date, which is about a little more than six months away from now. Again, this is an example and yours don't have to be that long. On top of that, your objective is to own your stock at a discount and by giving it a little more time than usual the chance of your stock swinging wildly is increased, allowing your options to get exercised.

Even if your options are not getting exercised, you still come out ahead by constantly receiving a stream of premiums and over time it will boost your account balance.

If your stocks swing wildly, the chance of your put options getting exercised is very great and that could be any time from now depending on how your stock is swinging and which way it is swinging. So that's why the six months that I chose is not very significant in relation to this (or your) option-playing strategy. Remember that the more time there is to expiration, the higher the premium the buyer has to pay you the seller of the options.

Suppose that you pick a long timeframe, the premium for that option will reflect the long timeframe, and, therefore, giving you more money regardless whether the option get exercised or not.

If one week or two weeks or one month, two months or three months, or whatever, and your options get exercised, you get to keep the premium that was meant for a six-month option contract which lasted only a short timeframe. So there you go: the six-month timeframe works favorably for you.

Do you see what is going on here?

You pick a long timeframe to earn big premiums in hope of your options being exercised in a short timeframe and therefore allowing you to repeat that same process over and over and over again, making you consistent streams of income while owning stocks cheaper than the market price.

Of course, it is not guaranteed that picking long timeframes will result in your options getting exercised frequently, but the chance of that happening is very good. On top of that, you're collecting the premiums in the meantime while you're looking to invest for the long term.

I want to share a secret with you:

For those of you who can spot trends of a stock -- and that is, whether the stock is swinging up or down in the near distance future -- you can sell the longer timeframes, say, six months to 18 months, so that you can get paid big premiums while your options will most likely get exercised in a very short timeframe, paying you the premiums that were meant for longer timeframes. For those of you who can't spot the trends, well, stick to the strategies outlined in this website and you'll do just fine.

As you can see, you can use this strategy over and over to keep generating income and be a long term investor and not worry about how the market is doing. This is kind of a peace of mind trade!

But here's the best part:

Let's assume that Exxon Mobil's is trading at just under $67.50 a share, say $66, at expiration. Now you're obligated to buy 100 shares of Exxon Mobil's at $67.50 a share (which comes to $6750 = 100 x $67.50.) Remember that at the time of this trade Exxon Mobil was trading at around $75 a share and now it is trading $10 lower.

Again, no worries! You're still ok. You already set aside that money in your account to cover the trade. After buying your 100 shares of Exxon Mobil's (at $67.50 a share instead of $75 a share) and then subtracting the premium you collected for the sale of the put option ($67.50-$2.50), you now own Exxon Mobil's at a discount price of $65.00 per share.

Do you see what just happened? You saved 13% on your purchase of Exxon Mobil's shares. Had you not decided to trade the put option and bought the stock outright at $75 a share instead, you would have still in the red because the stock is trading about $10 lower. So trading options has advantages because if the stock is up, down or sideway, you make money.

But what if the stock on XOM is going higher and the option is not getting exercised? Where is the discount? Well, in that case, you still have the premium to keep as pure profits while doing very little work, and you can repeat the same strategy on the same stock again or move on to a different stock. There are thousands of BLUE CHIP stocks that you can choose from. This way, it takes the guessing game of trying to predict which way the stock is going to go away from you. You don't care which way the stock is going, you still make money in the long haul.

You might wonder and ask, "Why do I have to go through all this trouble to buy Exxon Mobil while I can just wait for Exxon Mobil stock to drop and buy it outright?" I suppose you can if you're good at prognostication, but for those who cannot predict how the stock is going to be, this strategy works very well.

Now you have one more choice to make...

You can immediately turn around and sell your Exxon Mobil's shares for $66, a quick $100 profit (100 x [$66 - $65)]. At this point, your gain is $350.00 ($250 from premium + $100 sale of equity), a 5% return on your investment in a short period of time. You can repeat this pattern of trade over and over forever.

Or other alternative is that, you can just go ahead and keep them to maintain a long position in a solid Blue Chip stock that pays forward annual dividend yield of 4% and sell a covered call against your long position to make even more money. So using a combination of cash-secured put and covered call are great ways to earn huge returns long term wise. See my other tutorial on covered call.

No question about it, selling put options is a simple, versatile options strategy. Not only can you use this strategy to generate recurring income, you can use it to buy shares of good, quality companies at discounted prices.

However you choose to use the put selling strategy, it's a powerful tool for boosting returns.

One special note about selling put strategy is that it is a good time when the risks of selling put are balanced because people trade when risks are out of balance (or volatile). Risk is balanced means when stocks are calm and not volatile. So this strategy is good when underline stock is not volatile. So what you look for in stocks of this type are stocks that don't swing wildly regularly.

Here is a summary of the put strategy to help you understand better:

Buying Stocks at a Discount by Selling Put Options

Option traders have an advantage over stock traders because, when the timing is right, they can buy stocks at a discount. How do they do it? They sell put options on stocks they want to own and then wait for the price to fall. Sound complicated? Surprisingly, it's quite simple once you understand the basics. Let's start from the top and take a look at the first step you need to take to start putting this strategy to use in your own portfolio.

  • Step 1: Find a Stock You Want to Own.

    The first step to take when looking to buy stocks by selling puts is to find a stock that you would like to own. After all, in the end when you employ this strategy, you are hoping to own the stock as a part of your portfolio. And since you wouldn't just go out and buy any old stock in a standard stock trade, you shouldn't just settle for any old stock when implementing this strategy. This may seem obvious, but when we get into the next step, you will see that if you don't start with Step 1, it is easy to be tempted to simply sell puts on the stocks that are offering the highest premium-which can be a big mistake.

    When you're looking for stocks you would like to own, make sure you look for stocks with strong fundamentals -- especially in turbulent markets because they have a good chance of rebounding faster than other stocks.

  • Step 2: Sell Put Options

    Your next step to buying stocks at a discount is identifying which put option you are going to sell and then selling it. As an option seller, you have three choices when looking at which put option to sell. You can sell the at-the-money option (ATM), an out-of-the money option (OTM) or an in-the-money option (ITM). When selling puts to buy stocks, you are typically going to use an at-the-money put option. At-the-money options offer a nice balance between paying a good premium and giving you a good chance of actually having the stock put to you.

    The premium you receive for selling the put option directly impacts the discount you will get on your stock purchase if the stock is put to you. The higher the premium, the better the discount. As I mentioned above, some stocks offer extremely high premiums on their put options either because the stocks are extremely volatile or everybody believes the stock is going to be moving lower. If you haven't done your homework and determined that the stock is one you would want to own, you may be tempted to go for the stock with the highest premium. Don't fall into that trap and always do your homework!

  • Step 3: Manage Your Trade.

    Once you have sold your put option, it is time to sit back and see what happens to the price of the stock. Basically, one of the following four things can happen to the price of the stock:

    • The stock price can go up a lot
    • The stock price can go up a little
    • The stock price can go down a little
    • The stock price can down a lot
Let's take a look at what would happen in each scenario.

The Stock Price Goes Up A Lot: If the stock price goes up a lot after you sell the at-the-money put option, you don't have to do anything. [To be honest, you don't have to do anything at all after you sold your put options regardless of the scenarios -- the brokerage system takes care of everything.] The put you sold will expire worthless, and you get to keep the premium you received when you sold the put.

The Stock Price Goes Up a Little: If the stock price goes up a little after you sell the at-the-money put option, you most likely won't have to do anything. The put you sold will most likely either expire worthless or will expire with too little intrinsic value to be worth exercising. Both outcomes allow you to keep the premium you received when you sold the put.

The Stock Price Goes Down a Little: If the stock price goes down a little, the person who bought the put from you may choose to exercise the option, and you will have to buy the stock at the strike price set in the option. But since you sold the put on a stock you wanted to own anyway, this is a terrific result. You now own the stock you wanted, plus, you get to keep the premium you received when you sold the put. [Again, you don't have to do anything at all -- the brokerage system takes care of everything.]

The Stock Price Goes Down A Lot: If the stock price goes down a lot (below your breakeven point), the person who bought the put from you will definitely choose to exercise the option, and you will have to buy the stock at the strike price set in the option. But once again, since you sold the put on a stock you wanted to own anyway, this is a terrific result. You now own the stock you wanted, plus, you get to keep the premium you received when you sold the put. Of course, if you see the stock dropping below your breakeven point, and you decide you don't want to buy the stock after all, you can always buy back the put you sold and exit the trade.

Additional Bonus Strategies:

This strategy is a little advanced for you beginners but it's not too complicated because I'll layout the instruction in a clear and concise manner. This strategy is being used by experienced traders on a daily basis because it reduces risk and lowers your investment costs by balancing debit against credit. Again, this is just a bonus strategy and you do not need to use this strategy if you don't feel comfortable doing it.

Remember that in options you can buy or sell calls or puts. Buying calls or puts will cost you money in the amount of premiums you have to pay, while selling calls or puts will earn you money in premiums you receive from the buyer.

Here, we intend to buy one put contract and also sell one put contract simultaneously. This is called a bear put spread because this strategy profits if the stock trades downward.

Check out the tutorials on options spreads: Option Spread Strategies. NVDA Stock Options Play: (Taken out of my actual trade I've made that resulted in a very descend profit).

As of August 27, 2018, Nvidia (NVDA) stock was trading at $277 a share, so we want to buy NVDA October 19, 2018, $270 (strike) at $12.40 (premium) put, and sell NVDA September 28, 2018, at $265 (strike) @ $5.25 (premium) put for a $7.15 net debit ($12.40 - $5.25). Maximum risk on the trade is $715 per spread (100 * $7.15). Ideally, NVDA stock closes near the $265 strike price at September expiration to realize the maximum gain.

This trade strategy is widely being used by experienced traders to anticipate a pull back from NVDA recent run-up from around $253 a share to an all-time high of $282 a share. So traders expected this stock to take a breather from its fast run-up and make a pull back to around $260-65 a share within the timeframes of the trade. However, long term wise, traders expect NVDA to rise again. So experienced traders make use of this run-up and pull-back market cycle to their advantage.

In multple legs strategies, experienced traders use the buys and sells combination to increase odds of profitability while minimize risk and at the same time can lower investment cost by balancing debit and credit combinations. As you can see in the above example, you receive some credit to offset the debit that you have to pay and thus reduces your overall cost of the trade.

Make note of the $265 strike because I and other traders don't think that NVDA stock will drop much lower than $265, or worse case scenario, lower than $260 a share. They think the support level is between $260 to $265 a share within that timeframe. So if you anticipate a stock's support and resistance levels, you can use credit spread strategies to your advantage like experienced traders do on a regular basis.

You can mimmick this (bear put spread) trade on other stocks that have a short term bearish sentiment outlook within the timeframe of your trade. Use this example as one of your strategies to make trades on a regular basis to earn quick profits. The important key to remember is that, make sure you buy a put at the strike price higher (e.g., $270) than the selling strike price (e.g., $265) of the put. If you are approved of a trading level of 3, you can use this strategy to trade to your advantage.

Notice that the selling of the put has to have a shorter expiration date than the buying of the put -- September 28 vs. October 19. This is to give the stock a little more time to turn bearish because the stock may not garner enough bearish momentum from its recent runup. So give it a little extra time to give your position a chance to make a downsize bearish move. The gap between the two periods are not important and its based on your perception of the bearish sentiment of the stock. Try it on a regular basis and see for yourself.

Conclusion

Selling put options is a simple, versatile options strategy. Not only can you use this strategy to generate recurring income, you can use it to buy shares of good, quality companies at discounted prices.

There you have it, selling put options strategy is a powerful tool for boosting returns.

What is a covered call option?

A covered call option is when you buy (go long) on an underlining (stock), say, a Citygroup stock in the amount of $6700 (at $67 a share for 100 shares using your out-of-pocket money [no margin money]), and simultaneously turn around those shares and make a "call sell options" for options buyers to buy 'the right to own' your Citygroup stock in the future.

A simplier way of saying is that, you buy a stock in the process of giving up that stock to someone else so that you can collect premium in the process. You might wonder, if you think a stock is going to go up, why giving up the right to profit on that stock to someone else and collect only a tiny premium in the process?

Well, as always the case, it would be nice if your guess in which way a stock is heading is always correct. But your guess might not always correct and to protect your wrong side guess, you need to take steps to minimize your losses and maximize your gains as much as possible by using a covered call method of trading. But your gain won't be as limitless as if you hold that stock outright yourself. So you need to decide whether you want a consistent streams of income plus some upside potential or an outright upside potential.

Statistics show that consistent streams of income plus some upside potential such as using covered call method of trading is way more profitable than trying to hit a home run by buying a stock and hope for a huge move on the upside. However, occasionally it does happen. This tutorial's intention is not trying to hit a home run and getting rich very quick in a very short time but to consistently earn a descend return on your long term investment.

Let's see an example to help you understand better:

First, you buy, let's say, 100 shares of Citigroup to allow you to sell one contract. Buy as much as you want to sell covered calls. But for this example, we're going to buy 100 shares to cover one contract. As I write this (March 26, 2018), the stock is trading for around $67 per share. Your total cost should be around $6700 (plus commissions of $5 to $8). Again, this is an example, yours might be a cheaper stock.

Here's what you do:

In technical term, you would in your brokerage account web interface select the type of trades you want to trade: stocks or options. In this case, you want to trade stocks and you select 'stocks' from the panel and the interface displays the stock pane for you to buy or sell. You select the symbol of the stock, select the "Buy to Open" (you're opening a position as a buyer so that you can buy the stock -- and buying that stock outright paying full price), select the type of trade: market order or limit order and submit your order.

Note: the order of items mentioned in this web interface tutorial may be arranged in different order or placed at different configuration but they all should be there in your web interface.

Market order is where you will buy your stock at any price set by the market and limit order is where you set your price you want to buy and if your price is not met, your trade won't be executed.

Most experienced traders always set their own price in order to extract every penny available from the market since every penny multiplies hundreds and thousands of times can add to a significant sum of money.

So if you want your trade to be executed at any price on the market, just select "market order." For more, see my tutorial on "Introduction to Options."

Now wait for a few seconds for the trade to be executed by the brokerage system. Try to refresh your interface and double check if the trade is executed. If it is, you now own the stock you wanted. At anytime from now on you can decide whether to hold your stock outright for yourself or give other investors the right to profit from your stock by selling a covered call (also called writing a covered call.)

If you decide to write a covered call, go to the next step.

Second, turn around and sell a call option on the 100 shares of Citigroup you'd just bought. This is one call contract.

Notice that you don't actually use the term covered call in your order: you use call. The name covered call exists only in term of strategy in discussion and not in the actual trading technical term. So the covered call is actually a buy of the stock to go long and a sell of 'the right to own' that stock; hence, step 1: you buy the stock outright and step 2: you sell the 'right to own' your stock to someone else.

A typical options order entry screen interface platform for entering orders looks something like this:



Notice that the various key items in the screen interface maybe arranged in different order and location for different brokerage services interface, but all the items should be there.

In technical term, you would in your brokerage account web interface select the type of trades you want to trade: stocks or options. In this case, you want to trade options and you select 'options' from the panel and the interface displays the options pane for you to trade.

Next, select the symbol of the stock, select the expiration date, select the type of trade (in this case, a "Call"), select the "Sell to Open" (you're opening a position as a seller to sell the option and you're giving someone else the right to own your stock), select the quantity of the option [1 for one contract], select the price of the option premium you want to sell [again, in return, you receive the premium from the buyer].

That last item maybe calculated automatically by the brokerage system on some systems, and in that case, you only need to select the "strike price" instead of the "premium."

If you are not sure what price to sell, you can just select market order in which case your price will be whatever the market is trading at the time of your trade. Most experienced traders always set their own price in order to extract every penny available from the market since every penny multiplies hundreds and thousands of times can add up to a significant sum of money.

If you're not picky for having to give the market a few pennies here and there, you can just select "market order" and leave it to the mercy of the market to skim some pennies from you.

Next, click on "Preview" to see your order and if it's what you entered, click "Send" or "Order," depending your interface.

That is it! Very simple!

Now you don't have to do anything else but wait for the expiration date to arrive. Once it arrives, you don't even have to do anything at all; the brokerage system takes care of everything.

Meanwhile, you can start working on your next trade because at any time from now until expiration, your outstanding covered call option may get call~ed away from you (meaning get exercised). Once it does, you can pull the trigger on your next trade. Just keep repeating this process over and over and over again.

For Illustration Purpose:

[Remember? You buy a stock in the process of giving up that stock to someone else and earn premiums! That's the whole idea!].

In options lingo selling a "covered call" is called "writing a covered call." There are two steps for this process: Step 1: Buy the stock for the purpose of sell the right to own the stock to someone else. Step 2: Sell a call option or writing a call option. Writing a covered call option means that you're giving other investors the "right to buy" your 100 shares of your stock that you'd bought and currently are holding them. The call option you sold requires you to deliver your 100 shares of the stock if the option is exercised. That can happen anytime between the time you sold and the expiration date of the option. Remember that you need to hold your stock until the option expires.

As of this writing (March 26, 2018), the call option you want to sell is the Citygroup stock quoted for April 27, 2018 (expire in one month) with a strike price of $67.00 for a premium of $3.50 per share. OK, you bought a Citygroup stock at $67 a share and turn around and sell a covered call for the same amount as you bought them.

Why would a buyer of your option want to pay you $67 a share while he can purchase the same stock outright on the open market? [That was a trick question.] No, the buyer's intention was not to tie up their capital (in this case $6700) and only want to leverage their money (spending very little money to control a huge position).

But you, on the other hand, don't mind spending a huge capital on the stock. So it's kind of a "win-win" for both you and the buyer of your options. Let's face it! You put your money in your checking or savings accounts at your local banks to earn interest of about 1% or less anyway, and you're basically doing the same thing here but receiving way more returns on your investment.

You will receive the premium of $3.50 per share. By selling the call option, you collect $350 cash ($3.50 X 100 shares). You might wonder: how do I pick the right option to sell? There is no right or wrong answer to this question. You just pick one out of many possibilities and done with it! You don't need to use sophisticated method to quantify and tell you what the optimum price to trade because you're selling for premiums and the higher the premiums the better for you. But as a general rule of thumb, try to sell your call option at a strike price slightly higher than the price you paid for your stock or slightly higher than the current trading price of the stock.

I found that selling about 2 to 3 percentage points slightly higher than the current trading price of the stock is optimal, but then again, you don't have to stick to my taste of trading -- just pick a strike price slightly higher than the current trading price of the stock and you'll be on your way to profitability.

So the only key point to remember here is: pick a strike price slightly higher than the current trading price of the stock.

Remember that the more time there is until expiration, the larger the option premium the buyer must pay you [the seller] since the longer the time the more chance of a stock to go up in value. You don't care what the condition of the market is going to be during the timeframe, and you don't care if your stock is going up or not during that time. In other words, you don't care if your stock is going up, down or side way. Your strike price is set and you just received the premium and that's all you're looking for. So just a general rule of thumb: pick the highest premiums to trade! Not all the time but most of the time. I usually look at the open interest and see if there are a lot of contracts are being traded on a particular option, and that's the one I'm focusing on. So you sort of riding the "co-tail" of other traders.

[A side note: to those people who have IRA or 401k accounts: you can use this very safe investment strategy to boost your investment returns instead of invest in other types of investments. Signup an IRA account with a brokerage service and transfer your IRA/401k accounts to your account at the brokerage and start trading using this covered call strategy.]

Here's where the numbers get interesting.

You bought the stock for $6700 and you sold an option collecting $350 almost instantly and it is for one month and for one contract. That's a 5% return for doing very little work. This $350 is yours to keep no matter what happen to the option. But wait, it gets even better.

The call option you sold requires you to deliver your 100 shares of Citigroup if the option is exercised. That can happen anytime between now and the expiration date of April 27, 2018. Here's the great part if your option gets exercised (or get called away from you), you get $67 per share for your Citigroup stock or $6700 cash! In other words, you get your original investment in full! Again, this is an example using an ITM call. You can sell your options at out-of-the-money (OTM) as well, or even go deep ITM as well. Again, there is no right or wrong on the choice you make. But as a general rule of thumb, try to sell your call option at a strike price slightly higher than the price you paid for your stock or higher than the current price of the stock.

This is a safe strategy for guaranteed retirement income.

A little quick math shows you make $350 selling the option, plus a profit of $0 on the equity side if the option is exercised. That's $350 of pure profit on an investment of $6700. An easy money return of 5%. Notice in this example, the profit on equity side is $0 because I chose the strike price to be an ITM at exactly $67 a share. In your case, you might want to sell your strike price at a higher price than the price you bought your stock.

So the key point to remember here is: pick a strike price slightly higher than the current trading price of the stock.

One word about risk: you need to hold Citigroup stock until the option expires. If you sold your 100 shares of Citygroup prior to its option expiration date, you still owe option buyer 100 shares of Citygroup if that buyer decides to exercise his/her options and you must come up with 100 shares of Citygroup -- which usually means that you'll have to buy 100 shares of Citygroup at current price to pay back the buyer.

If Citigroup runs up to above $70.50 a share, whoever bought your call option is going to exercise their option and make a lot of money in the trade and laugh all the way to the bank. But you'll still make money from the deal -- (not as much as if you hadn't sold the call option). Notice for the buyer of your option, the stock has to trade above $70.50 to be a profitable trade because the buyer had to pay you the premium of $3.50 a share, so $67 + $3.50 is $70.50.

If Citigroup stays below $70.50, whoever bought your call option is not going to exercise their option; and therefore, leaving you holding the 100 shares of Citygroup for yourself. Of course your stock has fallen in value and worths less now. But you get to keep the money from selling the call option (premium $350) and the 100 shares of Citygroup.

Who knows giving it sufficient time, Citygroup stock may rise up in value substantially and even to a point you can make a profit from it. Not only that, as soon as the contract is settled or expired, you repeat the same process just outlined and make more money consistently. But you have to pick stable BLUE CHIP stocks and focusing on long term investment. Your stocks will swing wildly once since awhile but in the long run your stable BLUE CHIP stocks will go up and your investment will prosper.

I briefly mentioned about people with IRA/401k accounts can use this strategy to boost investment. For this strategy to work in your favor, you have to pick stable BLUE CHIP stocks and repeat the outlined process repeatedly in however timeframes you desire: whether it is monthly, quarterly, semi-annually or yearly, or even weekly. Be consistent with your timeframes--meaning be consistent picking your expiration dates.

You don't have to use all of the IRA/401k balances to use with this strategy. Just set aside a portion of the balances for this strategy and leave the rest with your other investment types. I wouldn't tell you to do it if it's not safe.

Remember that this is a long term investment strategy and we don't care what the market is doing daily, monthly, quarterly or yearly.

I'm sure you see the power in this simple technique and you can clearly see the thinking behind the use of the covered call method of options trading. It's a very good tool to use in almost any kind of market condition.

Examples of blue chip stocks are Walmart, Mcdonalds, Google, Apple, Facebook, Microsoft, Intel (INTC), 3M, AbbVie, Merck, Johnson & Johnson, Bristol Meyer, Exon Mobil, Chevron, Hess, Bank of America, Citygroup, Goldman Sach, Yum! Brands, Pepsi, Coca Cola, GM, Ford, etc. If you don't like the list that I mention here, there are thousands of blue chip stocks out there that you can choose from. You don't have to choose from the list here. You can find your own blue chip stocks that fit your personal preference.

Here are my top picks (as of March 31, 2018) in that preferential order for long term investment that you can use to trade cash-secured puts and covered calls:

1. NVIDIA Corporation (NVDA), stock price on March 27, 2018: $225.52 ===> to be a force in chips for video games, AI and machine-learning technologies, also continues to lead the charge in self-driving cars. My 5-year target: $320 a share. Most analysts have this stock at $825 a share on average in 5 years. But I like to keep my expectation low to avoid disappointment.

Update: October 27, 2020. Nivdia stock: $536/share.

The stock is now at $536/share (yeh!!!), surpassing my 5-year target of $320 per share. Better yet, this company is growing rapidly in a 'breakneck' speed through in-house inovations and outside acquistions. So the future is very bright. The management is very smart in using their 'skyrocket' high stock price to buy these valuable companies without denting their cash on-hand. That's what you can do when your company's stock is as high as NVIDIA is - it gives you leverage and power to do things that otherwise would not be possible.

Nvidia reminds me of Amazon just a few years ago when Amazon stock was already trading around $500 per share and the stock was moving up steadily ever since [February 26, 2016 at $555 per share; October 27, 2017 at $1,100 per share; May 11, 2018 at $1,603 per share; November 11, 2019 at $1739 per share; March 27, 2020 at $1,900 per share; May 29, 2020 at $2442 per share; September 4, 2020 at $3294 per share].

Let me clarify my view on this comparison: Nvidia is not Amazon nor will it perform like Amazon stock in the future. It will never be anything near what Amazon has done -- no stock is nor will be. However, the strategy that Nvidia employs recently resemblances the strategy that Amazon employed leading up to their current high performances of its stock.

The purchase of ARM is a very smart move by Nvidia's management and it will do a lot of good for the future of this company. Will its stock performs like Amazon's stock in the future? We'll see! And time will tell!

Here is the synopsis from the press release:

  • Unites NVIDIA's leadership in artificial intelligence with Arm's vast computing ecosystem to drive innovation for all customers


  • NVIDIA will expand Arm's R&D presence in Cambridge, UK, by establishing a world-class AI research and education center, and building an Arm/NVIDIA-powered AI supercomputer for groundbreaking research


  • NVIDIA will continue Arm's open-licensing model and customer neutrality and expand Arm's IP licensing portfolio with NVIDIA technology


  • Immediately accretive to NVIDIA's non-GAAP gross margin and EPS


  • Consideration of $40 billion to be met through a combination of NVIDIA shares and cash

Please see

NVIDIA to Acquire Arm for $40 Billion, Creating World's Premier Computing Company for the Age of AI

Update: July 2, 2020. Nivdia stock: $384/share, surpassing my 5-year target of $320 per share.

Update: November 16, 2018. Nivdia stock: $163/share.



Synopsis: Nvidia Stock Crashes After Earnings Guidance and Cryptocurrency Fears.

  • Record revenue from Datacenter, Professional Visualization, Automotive platforms

  • Quarterly cash dividend raised 7 percent to $0.16 per share

  • Company intends to return an additional $3 billion to shareholders through fiscal 2020

Nvidia shares fell steeply after the chipmaker gave weak fourth quarter revenue guidance when it reported third-quarter earnings after the close on Wednesday, November 15, 2018. I call it a "crash" based on from where the stock was trading around $280 to $293 a little over a month ago--October 2, to be more precise.

NVIDIA today (November 15, 2018) reported revenue for the third quarter ended Oct. 28, 2018, of $3.18 billion, up 21 percent from $2.64 billion a year earlier, and up 2 percent from $3.12 billion in the previous quarter.

"AI is advancing at an incredible pace across the world, driving record revenues for our datacenter platforms," said Jensen Huang, founder and CEO of NVIDIA. "Our introduction of Turing GPUs is a giant leap for computer graphics and AI, bringing the magic of real-time ray tracing to games and the biggest generational performance improvements we have ever delivered.

"Our near-term results reflect excess channel inventory post the crypto-currency boom, which will be corrected. Our market position and growth opportunities are stronger than ever. During the quarter, we launched new platforms to extend our architecture into new growth markets -- RAPIDS for machine learning, RTX Server for film rendering, and the T4 Cloud GPU for hyperscale and cloud."

Capital Return

During the first nine months of fiscal 2019, NVIDIA returned $1.13 billion to shareholders through a combination of $855 million in share repurchases and $273 million in quarterly cash dividends.

In November 2018, the board of directors authorized an additional $7 billion under the company's share repurchase program for a total of $7.94 billion available through the end of December 2022.

NVIDIA announced a 7 percent increase in its quarterly cash dividend to $0.16 per share from $0.15 per share, to be paid with its next quarterly cash dividend on December 21, 2018, to all shareholders of record on November 30, 2018.

NVIDIA intends to return an additional $3 billion to shareholders by the end of fiscal 2020, which may begin in the fourth quarter of fiscal 2019.

What does this mean for long term investors, which I am targeting?

Well, if you already own the stock, don't sell but hold on to it in hope that it will recover and maybe turn a profit in the long run, say, in five years. So don't panick!!!

Another excellent strategy is to buy more at these lower prices, turning it into a "dollar cost average" strategy that works wonderfully awesome over a period of time. That's what I would suggest you do: buy more shares at these lower prices and if the stock drops some more buy some more shares to make the dollar cost average works favorably for you.

Bottom line: the fundamental of the company is very much sound and you should stick to the long term horizon instead of panicking to crashes like this one. Remember that stocks rarely go up in a straight line; so the stock market is like sex: there's highs and there's lows and it feels the best just before it ends too soon and it never last long either. As with sex, you'll just have to keep trying for more to get the most out of it.

Here is my definition of "dollar cost average":

"Stocks rarely go up in a straight line."

Just remember that definition when you think of a dollar cost average.

Because of the nature of stocks, which rarely go up in a straight line, it makes a great strategy for a long term investment.

I'm not the only one who believe that this stock is going to go up in five years. Here is what WallStreet analysts are saying about Nvidia:


Goldman said it remains "Buy-rated on the stock as our view that Nvidia has access to
one of the best growth opportunity sets in Semis and that it has a sustainable
competitive lead within remains unchanged."
   


"The stock will likely not bounce back right away,
given the severity of the miss," Morgan Stanley said.
   


Wells Fargo Analyst:

Concerns (and now frustration) over a significant gaming channel inventory burn-off
have materialized ... While we can appreciate that NVIDIA's weak F4Q19 outlook is
impacted by a 1-2 quarter work-down of Pascal mid-range gaming card inventory in the
channel ($600M; assuming no sell-in in F4Q19 as crypto-related dynamics flush through
the channel), couple with a seasonal decline in game console builds, we think
investors will be frustrated by NVIDIA's comments exiting F2Q19 that:
"...we [NVIDIA] see inventory at the lower-ends of our stack...inventory is well
positioned for back-to-school and building season that's coming up on F3Q19..."

Bottom Line: Well, even if we model a strong double-digit growth in DCG next year,
we think there is a high likelihood that NVIDIA will not grow next year.
We are modeling for as such.

The large shortfall in guidance due to a bloated channel due to crypto-currency is in
sharp contrast to the comments around channel inventory from the company at the
last earnings call. Our estimates and target price are going lower.
We remain Market Perform rated.

We are Buyers on weakness.
   


SunTrust Analyst:

The surprisingly weak Q4 guide appears temporary.
NVDA guided Q4 20% below consensus revs as the company halts 1/3 of gaming segment sales
to flush channel inventory built during the crypto enthusiasm in 1H18.
This badly damages near-term revenue and profits, but Datacenter, Pro-Viz,
and Automotive results support our structural growth view.
Gaming resets our 2019 & 2020 EPS to $7.33 & $8.70 (from $8.18 & $9.59).
PT goes to $237 (from $316) based on 30x (17x discount to rapid-growth tech peers)
our CY20 EPS, discounted back 1 year. Buy.
   


RBC Analyst:

Going forward, we think the focus will now shift to Data Center as gaming expectations
are now reset due to crypto currencies and a product transition (Turing) which will
unlikely ramp until around the Jul-qtr time frame. Net Net: we lower our price target
due to the lower than expected results (PT to $260 from $310).
Positively, gaming and Pro Visualization will likely be up q/q in January helping gross
margins and offsetting the material gaming weakness.
   



2. Abbvie Inc (ABBV), stock price on March 23, 2018: $97.46 ===> a drugs maker selling top drugs like Humira, Revlimid, Enbrel, Rituxan, Herceptin, etc. The company announced in February 2018 that it set aside $10 billion for shares buybacks of about 87.6 million shares, or 5.5% of the shares outstanding, starting in May 2018 and continues to the end of the year.

Update: July 18, 2018.

AbbVie Synopsis

The performance of AbbVie (ABBV) shares through 2018 thus far up to June 30th can be characterized as lackluster. It has performed similar to the S&P 500 and is just above break-even at .8% return on the year. A lot of pessimism is built into the share price relating to two failed clinical tests by Rova T and Imbruvica. The stock market is beginning to question AbbVie's pipeline of 20 drugs and its ability to supplement the massive growth in sales of its Humira drug line.

Humira has been a massive success. It is an extremely profitable drug for AbbVie and it accounts for over 66% of its net revenue ($18.4 billion). The company secured a deal with Samsung Bioepis and partner Biogen (NASDAQ:BIIB) to fend off generics until 2022. It has been developing immunotherapy cancer drugs and is reliant on research and development to internally develop a Humira replacement which will decrease its reliance and revenue concentration risk.

Its second top-selling drug is called Imbruvica. This drug can differentiate between cancer cells and regular cells. It inhibits the growth of certain cancer cells caused by lymphoma and leukemia. Imbruvica will generate greater than $3.3 billion in sales during 2018 and management projects a terminal revenue level of $7 billion in sales in the next few years.

AbbVie is a cash flow machine, it generates $10 billion of free cash flow a year and it consistently increases the capital repatriation to shareholders. The company pays $3.76 dividend per share, which equates to a 3.94% yield based on a closing price of $95.41. This strong cash flow generation has created significant assets and the ability to leverage its balance sheet to make an acquisition to stave off revenue decline from the Humira patent expiration into 2022.

This isn't your typical one drug value trap biotech stock like Gilead (GILD); it has substantial growth opportunities in the pipeline and remains a candidate to make an acquisition.

Summary

  • AbbVie continues to grow its top line and bottom line as management raises guidance into the second half of 2018.

  • The share price looks attractive at these levels, and is trading at a discount to fundamental earnings.

  • A $10 billion buyback program put to use, combined with annual dividend increases, makes this company easy to hold as it develops its pipeline to supplement Humira sales.
Analysts estimate the 5-year revenue compound annual growth rate will average 17%, which is significant for a company with a $146-billion market capitalization. With the 5-year revenue compound annual growth rate on average of 17% should propel the company's market capitalization to around $300 billion or close to it.

This is a very solid company that consistently has increased its dividend regularly at a good percentage. My 5-year target: $200 a share.


As of July 31, 2018, I'm adding a new stock and squeeze it in as the third-rated stock: Texas Pacific Land Trust (TPL). This stock doesn't have options, so you can't use it to trade cash-secured puts and covered calls.



3. Texas Pacific Land Trust (TPL), stock price on July 31, 2018: $740.00 ===> Texas Pacific Land Trust was created in 1888 as a result of a bankruptcy of the Texas and Pacific Railway Company. A company, or more specifically a trust, that is trying to go out of business and ceased to exist. Why would I or anyone want to invest in a company that is trying to go out of business? As they say: "... the devil is in the detail." What is in the detail? Read on.

My 5-year target: $2800 a share -- a 3 1/2 times current price.

Update: June 1, 2020 ====> WARNING: Please read TPL's annual report filed on Form 10-K and Form 10-Q as TPL is undergoing a major change in the company's structure!!!

With the end of the Civil War in 1865, the Texas and Pacific Railway Company was created in 1871 with the goal of having a southern transcontinental railroad that rivaled its northern territory counterpart, the Transcontinel Railroad. See map below:



The Texas and Pacific Railway Company was given the right to build a southern transcontinental railroad from Marshall, Texas, to San Diego, California, with a condition that the company completed the rail line by a certain deadline specified in the federal charter.

At that time, the southern transcontinental railroad was the only railroad in Texas, and one of the few in the United States, to operate under a federal charter. Congress granted the charter on March 3, 1871 to the Texas and Pacific Railway Company to build a southern transcontinental railroad.

The company was granted a federal land grant of twenty sections of land per mile through California and forty sections through what are now Arizona and New Mexico; and the State of Texas (where there were no federal lands) agreed to grant Texas and Pacific Railway Company twenty sections per mile for the portion of the line crossing Texas.

The panic of 1873 caused financial difficulties, and by 1876 only 444 miles had been built. In 1879, Jay Gould bought the company and began laying track west. Gould merged Texas and Pacific Railway Company with Southern Pacific Railway, and by 1881 it had built a total of 972 miles of track, entitling it to 12.4 million acres of land granted in the federal charter. But because it had not built all of the line within the time required by its charter, Texas and Pacific Railway Company was awarded only 5,173,120 acres, later reduced to 4,917,074 acres - 3.5 million of that in Texas.

In 1888, the Texas and Pacific Railway Company went through bankruptcy and receivership, and the bondholders who financed the railroad were awarded the land in Texas that had been granted to Texas and Pacific Railway Company. The bondholders created a trust, Texas Pacific Land Trust, to liquidate those lands for the benefit of the bondholders, receiving 3.5 million acres of land.

The certificates of trust issued to the bondholders were later converted to shares and listed on the New York Stock Exchange (NYSE: TPL). Those orginal shares have been split several times since and making the shares outstanding larger than the original shares when bond certificates were converted. Since then, descendence of original bondholders have sold off their shares to other investors like you and me in the open market, but a very small number of them still retained a small portion of their original holdings.

The Trust was created to manage and sell the land and eventually go out of business. They have been trying to do just that for the last 130 years. As trying it maybe, the trust seems to be in no hurry to put itself out of business.

Today, the Trust is one of the largest landowners in Texas with around 888,333 acres located in eighteen different counties. Texas Pacific Land Trust derives revenue from all avenues of managing the land, i.e. oil and gas royalties, grazing leases, easements, sundry and specialty leases, and land sales. The Trust has a perpetual oil and gas royalty interest in some 459,200 acres.

The mineral estate under the land was spun off into a separate entity and later sold to Texaco, now Chevron. TPLT owns a royalty interest in some 459,200 acres of its land.

Grants of land to railroads were done on a checkerboard pattern, granting the railroad every other section in portions of the State not yet settled. The idea was that, when the railroad sold off the land, settlement and development would be encouraged along the rail line, making the sections retained by the state more valuable and ripe for settlement.

Most of the sections of the land retained by the State of Texas is owned by the University of Texas when the State of Texas granted the University of Texas most of those sections some long time ago. Today, the land is managed by the University of Texas Endowment Fund, and the University of Texas Endowment Fund earns subtstantially of investment income from oil and gas royalties from the land.

The discovery of oil in West Texas during the late 1920s and later in East Texas had a major impact on the company. During the years of peak crude oil movement the physical condition of the railroad was significantly improved, and the Texas and Pacific was able to weather the Great Depression better than many of the other railroads in the region.

Most TPLT lands are in El Paso, Hudspeth, Culberson, Reeves, Pecos, Winkler, Excor, Midland and Glasscock Counties. Much of TPLT's land is now in the heart of the Permian Basin, the hottest area of oil and gas exploitation in the nation. As a result, the value of shares of TPLT have soared, from a low of $156.60 per share in August 2015 to $740 at close on July 31, 2018.

Permian Basin daily production as a whole has soared to 3.3 million barrels of oil and nearly 11 billion cubic feet of natural gas during the month of June, 2018, according to the Energy Information Administration. TPLT revenue is derived from oil and gas from most of the output from the Permian Basin drillers, particularly, Chevron.

For a number of years past the Trust have followed the practice of declaring an annual cash dividend at their meeting typically is being held in the month of February each year. So if you're a shareholder of this trust make sure that you don't sell your holding during the first quarter of each year because you'll be missing out a possible dividend and special dividend payouts. Here is the dividend history for the past few years:

Payment Type Declared Date Payable Date Amount
Annual Regular Dividend February 25, 2016 March 16, 2016 $.31
Annual Regular Dividend February 21, 2017 March 9, 2017 $.35
One-time Special Dividend February 21, 2017 March 9, 2017 $1.00
Annual Regular Dividend February 21, 2018 March 16, 2018 $1.05
One-time Special Dividend February 21, 2018 March 16, 2018 $3.00
Annual Regular Dividend February 25, 2019 March 15, 2019 $1.75
One-time Special Dividend February 25, 2019 March 15, 2019 $4.25
Annual Regular Dividend February 24, 2020 March 16, 2020 $16.00

As of 2020, it's the sixteenth consecutive year that the annual dividend has been increased.

Summary

Original bond certificates were converted into shares of this trust and is trading in the NYSE: TPL, and these shares are required to be retired eventually and the trust will go out of business and ceased to exist.

So, how do they retire these shares? Why did it take over 130 years already trying to get rid of the shares and the trust and to no avail?

The trust's mandate was to get rid of itself by selling off lands and other properties and go out of business. Sounds like a simple idea to do, but with these valuable minerals on its properties, it's very hard to go out of business -- [to the pleasure of its shareholders.]

So the answer is: It's very hard to go out of business when you have a stream of income and the land keeps going up in value all the time. As one would expect, the trust is in no hurry to go out of business but at the same time is trying to sell off lands and other properties and using that proceeds to buy back shares in the open market and retire those shares.

So the trust isn't going out of business any time soon. To understand the significance of the trust's longivity, put yourself in the shoes of the people who are running the trust where their future is dependent on the trust's on going future as well.

Consider this:

As a General Agent, Chief Executive Officer and Secretary at TEXAS PACIFIC LAND TRUST, Tyler Glover made $699,250 in total compensation in 2017. Of this total $381,250 was received as a salary, $300,000 was received as a bonus, $0 was received in stock options, $0 was awarded as stock and $18,000 came from other types of compensation. This information is according to proxy statements filed with the SEC for the 2017 fiscal year. This is not taking into account other perks and insider privileges that these officers are receiving and benefiting annually. So the actual amount is much much higher than the required report to the SEC.

Other officers of the trust received similar compensation, which means that, their livelyhood is tied to the trust's longivity--the longer the trust stays in business the more money they make.

So understandably, it seems that the trust is trying to sell less valuable lands and other properties little by little and using the proceeds to buy off shares and retire them, while keeping the most valuable lands and other properties that are producing consistent income to the end, and that's why it takes a long time to go out of business. Put yourself in the shoes of these people and you'll realize that life can be this so easy.

Update: June 1, 2020 ====> WARNING: Please read TPL's annual report filed on Form 10-K and Form 10-Q as TPL is undergoing a major change in the company's structure!!!

This means that the shares outstanding will decrease over time, little by little, while the stream of income just keep coming, driving the stock price higher and higher and higher, hence lands this stock in the third ranking of my pick.

This stock could conceivably be at $10,000 a share when it winds down to the last lot of shares that the trust is buying and retiring them. But when will the last lot be bought out? Judging by the pace of the trust, it looks like at least 50 more years before this trust is out of business. What does it mean as a shareholder of this trust to be the last lot of the shares to be bought out?

It means that your shares will be bought out at that price. Since everybody is trying to hold on to their shares the stock price will remain high to the end, unlike other stocks where shareholders may view that their shares may not find enough buyers.

With this stock, we know that the trust will have to buy back the remaining shares outstanding, so there is an absolute certain that the shares will be bought out eventually -- the trust has no choice but to buy out the shares -- that's what its mission is.

Imagine this:

Update: June 1, 2020 ====> WARNING: Please read TPL's annual report filed on Form 10-K and Form 10-Q as TPL is undergoing a major change in the company's structure!!!

You're among the last lot of shares to be bought out by the trust to cease to exist. At that time, the trust would still have some pieces of valuable land to get rid of and it tries to get the highest bid for the lands. Once the pieces of land are sold, the proceeds are used to buy the remaining lot of shares to close out the trust.

The intrigue is the value of the last lot of the lands to be sold and how many shares the trust still holds at that time. So the final share price to be bought out is dependence on the total proceed of the sale and the total number of remaining shares -- and at the present time, no one can value that price this far out into the future.

What if the trust tries to keep the most valuable lands for the last lot as that is the most likely scenario? Why wouldn't the trust tries to keep the most valuable assets and generating substantial income for shareholders til the end? It makes a lot of sense in that regard and no one in the right mind would disagree with that assumption.

If that is an indication of the scenario, judging by its pass pattern and lengthy history, the trust have always tried to balance the value of its land portfolio that is beneficial to all shareholders, whether you're the first or the last lot of shareholders to be bought out. The possibility of the trust keeping more valuable lands for the end lot is enourmous. That is why it is so intrigue to hold on to your shares to the end.

This means that if you're a shareholder of this stock, the chance of you getting your money back in full is very tremendously--plus along the line you will receive dividends as well. Over time, your investment in this stock will prosper. That's my gift to you!!! And you're very welcome!!!

Update: June 1, 2020 ====> WARNING: Please read TPL's annual report filed on Form 10-K and Form 10-Q as TPL is undergoing a major change in the company's structure!!!


4. Micron Technology Inc. (MU), stock price on March 27, 2018: $52.40 ===> Semi-conductor giant is leading the pack in DRAM, GDDR6, low-power DDR4 (LPDDR4) product. Moving forward, Micron is setting its sights on the self-driving car industry with a high-end memory solution. Car companies can achieve the 300GB per second data transfer rate in their fully-autonomous cars with the help of Micron's GDDR6. My 5-year target: $118 a share.

Update: May 29, 2018.

In conjunction with Micron's plans to return at least 50% of free cash flow to shareholders next year (2019), Micron Technology Inc. announced on Monday, May 28, 2018, that it plans a shares buybacks program worth $10 billion and will begin the buybacks in its 2019 fiscal year, which starts in September 2018 and lasts through September 2019. So the future of this stock is bright!!!


5. Anadarko Petroleum (NYSE: APC), stock price on March 23, 2018: $61.56 ===> recently (3-21-18) authorized buybacks of shares worth $3 billion or 9% of shares outstanding (significant and stock should rise plus this is a solid company that pays dividends). My 5-year target: $95 a share.

Update: August 1, 2019: Stock price on August 1, 2019: $74.31

The bidding war between Chevron Corp and Occidental Petroleum has come to the conclusion with Occidental Petroleum winning the war. Occidental Petroleum's $38 billion acquisition of Anadarko Petroleum could close on August 8, 2019. Occidental Petroleum is offering to buy Anadarko for about $73.46 a share, a 57% premium over the stock's closing stock price on April 11, 2019, the day before Anadarko said it had a merger agreement with Chevron Corp. But since then, Occidental Petroleum had convinced Anadarko Petroleum's Board to accept its offer while chunning Chevron Corp. Anadarko Petroleum's stock price on April 11 was $46.80. Now the deal would be paid for 78% in cash and 22% in stock. So the stock is now ("post-merger") tradeable in Occidental Petroleum shares.


6. Exxon Mobil (NYSE: XOM), stock price on March 29, 2018: $74.36 ===> My 10-year target: $136 a share. Ten years? Why so long? Population increases at an exponential rate and so are the energy uses, and, therefore, the 'mother' of all energy giants is the safest play. Stock should rise with very little downsize risks, plus this is a very solid company that pays dividends.

Update: September 23, 2020: Stock price on September 23, 2020: $34.39 per share.

Well, what happens to my price target of $136 per share by 2028? Will it achieve a $136 per share target by the year 2028?

The way it is going, it doesn't look like it will achieve that price target at all; however, there is still time left, but don't hold your breath, though.

A good long term strategy is to use "dollar-cost-average" strategy: That is, keep buy the stock periodically whether the stock is going up or down. This way, when the stock is going down, like we're seeing it right now, you buy the stock at a cheaper price and therefore you stand to reap a huge gain even the stock moves just a few points above the current price.

In other words, it offsets the losses that you bought at higher prices quicker. It might even turn a profit if you keep buying the stock at (these) low prices.

This is called "dollar-cost-average" strategy. It works wonderfully well long term wise. But you have to buy it consistently and periodically.

Take a look at this article that was written on September 23, 2020:


Buy Exxon Mobil Stock While It's Still Deeply Unpopular Another key factor that I based my projection on is that in ten years shale oil -- unlike Middle East oil -- will peak and supply glut as we have today won't be there. Global oil demand is expected to increase on average of 1% per year from 99.1 million barrels a day this year (2018), but global oil supply stood on average at 98.8 million barrels a day in June 2018 and not expected to keep up with the demand's rate of increase in the future, according to the International Energy Agency.

As of this writing (March 31, 2018) WTI Crude oil prices are trading around $65 a barrel while Brent Crude oil prices are trading around $70 a barrel; and average gasoline prices at the pump at about $2.54 a gallon nationwide. These prices are expected to rise significantly in five to ten years which translate into higher profits for oil companies.

Shale oil rigs have a maximum life expectancy of about three years -- meaning that after three years of pumping oil from the shale well the oil is exausted and is abandoned and move on to other new wells. At some point, we're going to run out of places to dig for shale oil, and that some point is ten years away (in my mind.) Check out this article by Bloomberg titled: "Shale Skeptic Forecasts Imminent Demise for Permian and Eagle Ford," in which a shale oil skeptic raising a huge red flag saying that the shale oil's days are numbered in the Permian and Eagle Ford basin. Of course, it's only one man's opinion and he was wrong before. Many people in the industry disagree strongly with the man. What does he mean by ".... days are numbered?" One year? Two years? Three years? How many years? Or -- how many days exactly? That's what I'm interested in!!! My guess is that he meant 10 years or less.


7. QEP Resources (NYSE: QEP), stock price on March 23, 2018: $9.52 ===> recently (3-1-18) authorized buybacks of shares worth $1.25 billion or 54.3% of shares outstanding (very huge and stock should rise based on an unheard of a 54% buyback, plus this is a solid company as well). My 5-year target: $38 a share.


Note: these stock price projections are based on my own forward-looking analysis and not an indication of the actual future stock price performance. In other words, it's a guess! If you do play, please do so based on your risk-tolerance and affordability and target your timeframes of at least five years.


You might wonder that if I think these stocks are going higher in five years, and ask, "Why don't I recommend everybody to just buy the stocks outright and hold for at least five years?" After all, the gains may well be a lot more than the premiums received, "Why giving up the upside potential to other investors?" And on top of that you have the money to buy the stocks outright in the first place, "Why not forget about the selling of the covered call and keep the stocks for the long haul?"

I don't have a good answer to these questions other than to say if you're looking to receive consistent income with some upside potential and minimize your downsize risks, then use the covered call strategy; if, on the other hand, you're looking for huge gains but expose yourself to some downside risks, then buying and holding the stocks outright for the long haul is also ok.

These strategies fit some people's tastes but not others. You also can even do both, say, like putting half of the money aside for the covered call strategy and using the other half of the money to buy these stocks outright and hold them for the long haul. This way, you get to have both worlds!

Not only that, you can use covered call in conjunction with the cash-secured put strategy. If you really want a limitless upside potential, say, if these stocks mentioned in my picks or in your own picks go sky high and you don't want to give anyone the right to own your stocks, you would sell cash-secured puts on the stocks that you already own.

But instead of merely putting your money in your account to cover the cash-secured puts, you would buy these stocks outright (and holding them) and sell cash-secured puts against them.

This way, if the stocks rise you get to keep the premiums and the stocks, because the cash-secured puts that you sold are worthless to the buyers and they are not going to exercise the options. In other words, you get to have both worlds!

Another strategy that achieves the goal of a covered call is to use leverage (spending very little of your own money but control a huge position) to gain huge upside potential. Yes, there is a way to trade options (or covered calls) for long term investors without worrying that the expiration is approaching too soon. This is the same way you buy and hold stocks for the long haul but you only have to pay only the premium amount instead of the whole stock price.

The longest options contracts can be traded are for up to two years but the majority of them can be traded at about 12 to 18 months. For long term investors, this is too short of a timeframe to give your stocks the chances to go up in value. So using my strategy you can increase this timeframe for years and years and invest for the long haul but you only have to spend very little of your own money to control a huge position without using margin money.

Although, some of you can even increase your leverage even more by using margin money, my strategy doesn't involved margin money and that's why it is a very low-risk strategy that offers very huge upside potential.

So instead of spending lots of money to buy stocks to sell covered calls, say, in the amount of $1,000, $2,000, $3,000, $4,000 or whatever the amount is, you only have to spend only for the premium amount, say, $50, $100, $200 or whatever the premium amount is, to control a huge position for the long haul for a long term investment.

So in effect, you only spend very little of your own money to control a huge position for longer periods of time for long term investors.

Wouldn't that sound great if only you have to spend very little of your own money with only the risk is the only premium you paid and the contract is lasting a long time?

The answer is a soundly: "Yes!!!"

But this strategy is for those of you who have advanced trading accounts: level 2, 3 and have a membership with my paid "premium subscribers." Yes, this will cost you money to join as it offers you tremendous upsize potential.

On top of that in the near distance future, I will offer a subscription membership for those of you who want to earn more money aggressively using advanced strategies. My advanced strategies offer you multitudes of opportunities for aggressive investors to earn high returns in a short amount of time; and of course using safe and sound strategies.

For a very small, and negligible fee, I may in the future offer my expertise to manage an account for you for those of you who are too busy, too lazy, and don't want to waste time managing your own account but also at the same time just want an expert like myself to manage an account for you. You open an account with a brokerage service, give me the credential access only to trade your account [but not anything else] while you have full access to your account. My purpose is to trade only and nothing else so that you have full control of your account at any time. That is forthcoming for some of you!

Safety is what I stride to be for myself and for my members. I will only recommend trades that have very high probability of winning or else I won't even touch them with a ten-foot pole. Please stay tuned for further announcements per time allows. At the present time I'm too busy!!!]

[A side note: For some of you, you might want to apply for a level 2 or level 3 trading account if you want to play a naked put or naked call strategy or join in with my advanced strategies in the paid "premium subscribers" membership account to achieve high returns while maintaining high safety net. Level 2 and 3 are advanced strategies that give you leverages. See my tutorial on "Get started trading options."

So selling (or writing) covered calls and cash-secured puts is a great way to earn consistent streams of income and also gives you a limitless upside potential. If you do this consistently for 10 to 15 years you'll be on your way to your financial independence provided you start out at least $2,000 and don't take out any proceeds.

Remember that the more money you start out with or add more money in subsequent periods during your investment horizon the quicker your financial independence you'll achieve.

As they say:

"Give what you CAN, take WHAT YOU NEED!...."

I did my part and we don't need to get rich quickly! Focus for the long term and don't forget to thank me later!

Good Luck Trading!!!



A Brief Overview of Buying Puts and Calls

In my other tutorials about selling puts and covered calls, we mainly talked about selling of the options. But here, we will mainly talk about buying of the options: buying puts and calls -- or more specifically, naked puts and naked calls as oppose to cash-secured (covered) puts and covered calls.

To refresh your memory from my one other tutorial called "introduction to options": Buying call options is to go long -- betting that the stock option will rise so that you can profit from the rising stock option while paying only the premium to the seller of the call option. Now you're a buyer whereas in the other two tutorials (selling puts and covered calls), you were a seller.

Likewise, buying put options is to go short -- betting that the stock option will fall so that you can profit from the falling stock option while also paying only the premium to the seller of the put option. Simple enough?

In either cases, puts or calls, your losses are limited to just the premiums you paid to the sellers, but your upsize potential reward is limitless. You leverage your position by spending very little of your own money to control huge position in stocks, and, therefore, control huge upsize potential.

The technical process in using the web interface is the same as in the other tutorials but only differ from the "Sell to Open" [to open a position as a seller of the options in the other tutorials] to "Buy to Open," (here) to open a position as a buyer of the options.

A typical stocks/options order entry screen interface platform for entering orders looks something like this:



Notice that the various key items in the screen interface maybe arranged in different order and location for different brokerage services interface, but all the items should be there.

In technical term, you would in your brokerage account web interface select the type of trades you want to trade: stocks or options. In this case, you want to trade options and you select 'options' from the panel and the interface displays the options pane for you to trade.

Next, select the symbol of the stock, select the expiration date, select the type of trade (in this case, either a "Call" or a "Put"), select the "Buy to Open" (you're opening a position as a buyer of either a "call" [you're opening a long position] or a "put" [you're opening a short position]), select the quantity of the option [1 for one contract], select the price of the option premium you want to buy.

If you are not sure what price to buy, you can just select market order in which case your price will be whatever the market is trading at the time of your trade. Next, click on "Preview" to see your order and if it's what you entered, click "Send" or "Order," depending your interface.

That is it! A brief overview of how to buy puts and calls.

A Long Term Investment for Kids/Teens


If you have kids/teens and want them to get interested and learn how to invest/save for their future, it's not too early to start getting them interested in investing and saving by exposing them early in their early age years to the world of savings accounts and stock market investing.

One company called Stockpile (https://www.stockpile.com/) is aiming to bring fractional share investing to mainstream investors, particularly millenials and kids/teens who lack the huge sum of money and knowledge of investing. Stockpile has raised $30 million to continue its mission.

The company received its latest cash injection from the Fidelity-backed Eight Roads Ventures, alongside traditional venture funds like Mayfield, Arbor Ventures, Hanna Ventures, Wang Ventures, and others.

"We're on a mission to make it simple for everyone -- especially young, first-time investors -- to save and invest for their future," said Avi Lele, Stockpile's founder and chief executive, in a statement. "Fractional shares make market investing fun, easy, and personal. Even someone with only a few dollars can buy a piece of a favorite brand like Amazon or Alphabet, which are currently trading close to $1600 a share," (as of this writing April 2018)

Stockpile users can open an account online or using the company's iPhone or Android app. The account is free to open, but trades cost 99 cents per trade compare to $5 to $12 per trade for traditional discount brokerage services like Fidelity Investments, Ally Financial, E-Trade, Charles Schwap, Scottrade, TD Ameritrade, Tradestation, etc.

Using the app to browse for potential investments is relatively easy. Once a user downloads the app they can browse for potential investments under categories like "Entertainment", "Kids", "Technology", and "Food."

Rather than organize the potential stock purchases under companies, the app lists the underlying brands that a user might be familiar with, and links that brand to its parent company. Which means that if a user likes the "Malibu" brand they can search for the brand and then be taken to the option to buy GM stock without having to know that the brand is owned by General Motors Company.

The company offers some basic information on the stock market in its learning section (really just some definitions of common financial terms and a bit of the arcana around stock dividends and the language of earnings reports).

Pretty much though, an investor using Stockpile is on their own. It's only a little better than picking a horse in a race because a gambler likes the name. The app pretty much makes a user rely on their feelings about a company's brand to guide their hand when making investment decisions.

Stockpile has had tremendous success in attracting the next generation of investors, and their innovative approach takes the mystery out of stock investing and opens up access to all. They sort of like putting the stock market on a gift card in similar fashion that you would normally do to your kids' periodic allowances.

Instead of putting money in a gift card for their periodic allowances for your kids/teens for their personal use, why not open up an account with Stockpile and expose them to investing/saving?

It's never too early to get your kids/teens exposed to investing/saving and you don't have to have a lot of money to do it. So start early and the sooner the better for your kids/teens! Point them in the right direction and let them see the horizon!!!

On the Long Term Investment Front There is a New Type of Investment Technique Called "Robo Advisor."

April 10 2018

A fee-free robo advisor is the latest fintech to land millions in funding.

WiseBanyan raised $6.6 million in their latest round, according to documents filed with the SEC. At a base level, the platform offers robo-investing services with no management, trading or rebalancing costs. Fees kick in when clients purchase a la carte premium services like detailed investment strategies, increased personalization or additional automation services, the firm's website says.

The increased personalization allows clients to pick and choose the services that they find most appealing.

The New York-based firm currently has $153 million in assets under management and 32,000 clients, according to their latest Form ADV filed in March. There are 32 investors currently on the offering, according to the SEC filing.

The filing highlights continued investor support for robo advisors, though a number of industry executives have questioned the sustainability of the independent model. The largest independent digital advice platforms have found millions in funding, including Wealthfront's latest round that secured $75 million in January and Betterment's $70 million last July.

Fending off challenges from larger incumbents and upstart mobile investment apps, Wealthfront landed its latest influx with a continued focus on adding more to its digital-only platform, such as its PATH financial planning feature. It has also expanded its product offerings, though its latest risk parity fund quickly became a magnet for controversy.

Hybrid advice firm Personal Capital took a different approach after securing $40 million in funding last August. Up against comparable hybrid offerings from Vanguard and Schwab, the firm reinvested in its advisor base, hiring new employees in multiple cities across the country. Betterment has taken a similar approach, directing some of its funding to retooling and expanding the appeal of its RIA platform offering.

While the competition continues to evolve in the robo space, online retirement platforms have pushed the boundaries of digital advice as well. For example, Financial Engines, an online 401(k) financial advisory firm, teamed up with human resources giant ADP to offer their digital platform to millions of potential new clients on ADP's employer network.

For now, WiseBanyan is betting a focus on clients -- not assets -- will drive continued growth for the firm, its website says.

Co-founder Vicki Zhou started the firm in 2014, according to SEC documents. With dual degrees in applied math and biomedical engineering from Johns Hopkins University, she previously co-founded a medical device company and invented a patented surgical device, according to the firm.

WiseBanyan completed its seed funding round in 2015, which included John Hancock Investments as an investor.

What is a Stop Loss?


A stop loss is a type of order designed to protect investors from significant losses. It is an automatic order trigger that automatically activated once a price condition is met.

One of the most commonly used methods for limiting losses from a declining stock is to place a stop-loss order. Using this order, the trader will set the value (or price) based on the maximum loss he or she is willing to absorb. Should the share price drop below this value, the stop loss turns into a market order and will be triggered a sell order. Once the price falls below the stop level, the position will be sold and closed at the current market price, which prevents any further losses.

Online brokers offer various types of orders designed to protect investors from significant losses. The most commonly used order is a stop loss, but active traders should also consider using the trailing stop (loss). When these tools are combined, they become even more powerful. See trailing stop next section.

A stop loss can be implemented during the initial entry point (buying) or at any time thereafer. A typical stocks/options order entry screen interface platform for entering orders looks something like this:



Notice that the various key items in the screen interface maybe arranged in different order and location for different brokerage services interface, but all the items should be there.

As you can see from the screen interface, you can set your stop loss by clicking the bullit point option under price category. You can use the same screen to place a "stop loss" order on the position you already hold -- the existing position that doesn't have a stop loss on it. If you need to modify a "stop loss" on a position that already have a "stop loss" on it, you need to cancel it and start over again. If you're not sure on how to do it, just ask your brokerage service agent for help.

An example of how it works:

Suppose you're buying 100 shares of a stock that is currently trading at $10.50 a share. In the the price category stop option, click on the bullit point and enter the price, say $9, you want to sell your stock in the box next to the stop option. [Self-explanatory]

What is a Trailing Stop?


A trailing stop loss is an automatic order or auto pilot order that monitors and adjusts the stop loss accordingly based on the movement of the stock. It trails or follows the price movement of the stock by the margin of value you specified.

Whereas a regular stop loss has a fixed value and can be manually readjusted, the trailing stop automatically shadows the price movement, following the stock's rising price action. Over a period of time, the trailing stop will self-adjust, moving from minimizing losses to protecting profits as the price reaches new highs.

The trailing stop offers a clear advantage in that it is more flexible than a fixed stop loss. It allows the trader to continue protecting capital if the price drops, but as soon as the price increases, the trailing feature kicks in, allowing for an eventual protection of profit while still reducing the risk to capital.

To better understand a trailing stop, let's consider an example. If you have a $10 stock, you could set the trailing value as a fixed percentage of 5% or a fixed spread of, say, 20 cents. Either way, the trailing stop will follow the day's high by the predefined amount.

The important thing to remember is that if the last price drops below the trailing-stop value, the stop loss will be triggered. So, setting a stop too close may cause you to get stopped out more quickly than you hoped.

Another important thing to note is that stocks often move up a point or two or move down a point or two during the day, but at the close of the trading day moves back to a neutral position where it started the day.

If you placed a trailing stop too close you end the day with your position closed and the stock didn't go anywhere and therefore you accomplished nothing. So be judious about where you place your stop.

One of the greatest features of a trailing stop is that it allows you to specify the amount you are willing to lose without limiting the amount of profit you will take. In addition, trailing stops can be used with stocks, options and futures exchanges that support a traditional stop-loss order. Refer to the screen interface shown above for reference.

Note that some brokerage services screen interface, they place the trailing stop inside the advanced orders category area. So look around in your screen interface to locate it. For example, for this particular brokerage's screen interface it looks something like this:



Notice that when you click on the drop-down menu in the Adavanced Orders it shows the advanced orders options, including the trailing stop loss.

Examples of a Trailing Stop

Consider a stock with a:

Purchase price = $10

Last price at time of setting trailing stop = $10.05

Trailing amount = 20 cents

Immediate effective stop-loss value = $9.85

If the market price climbs to $10.97, your trailing-stop value will rise to $10.77. If the last price now drops to $10.90, your stop value will remain intact at $10.77. If the price continues to drop, this time to $10.76, it will penetrate your stop level, immediately triggering a market order. Your order would be submitted based on a last price of $10.76.

Assuming that the bid price was $10.75 at the time, the position would be closed [sold] at this point and price. The net gain would be 75 cents per share less commissions.

During a temporary price dip, it's important that you don't don't reset your trailing stop. If you do, your effective stop loss may end up lower than what you had bargained for. By the same token, reining in a trailing stop loss is advisable when you see momentum peaking in the charts, especially when the stock is hitting a new high.

Take another look at the example above. When the last price hits $10.80, a trader can tighten the trailing stop from 20 cents to 11 cents. This allows for some flexibility in the stock's price movement while ensuring that the stop is triggered before a substantial pullback can occur.

A good active trader always maintains the option to close a position at any time by submitting a sell order at market. Just be sure to cancel any trailing stops you have set, or you could find yourself in a short trade. (Trailing stops work equally well on short positions, but you want to make sure you don't get into a short position by accident!)

The Best of Both Worlds

One of the best ways to maximize the benefits of a trailing stop and a traditional stop loss is to combine them. When you do, it is important to note that initially the trailing stop should be deeper than your regular stop loss. It's also important to always calculate your maximum risk tolerance and then set the main stop loss accordingly.

For example, you could set a stop loss set at 2% below the current stock price and the trailing stop at 2.5% below the current stock price. As the stock price increases, the trailing stop will surpass the fixed stop loss, making it redundant or obsolete. Any further price increases will mean further minimizing potential losses with each upward price tick.

In other words, initially, the stock was given some flexibility with the staggered values, so it could establish a level of support. By doing this, you can trail a stock's price movements without getting stopped out early in the game, and allow for some price fluctuation as the stock finds support and momentum. Be sure to cancel your original stop loss when the trailing stop surpasses it.

The added protection here is that the trailing stop will only move up. During market hours, the trailing feature will consistently recalculate the stop's trigger point. Basically, if the price doesn't change, then neither will the value of the stop.

There you have it! Never establish a position without implementing either a Trailing-Stop or a Stop-Loss or both the Trailing-Stop/Stop-Loss as a Combo. It's a very smart way to invest for short term or long term.


Can you set a stop loss on options?

A quick answer is 'Yes!'

As with all stock orders which allow you to set stop loss and trailing stop loss orders, options orders also allow you to set stop loss and trailing stop loss orders.

There are two ways that you can go about setting stops on your Options trades and both methods work well whether you are day trading or swing trading. One way is to set it as a percentage (%) stop loss of the price of the options and another is to set it using the actual price of the stock. Make note: one using option price and another using stock price.

Method 1: Using Options Price in Percentage (%) Stop Loss

This is basically when you take an option trade and set a stop loss on the contract price itself (usually called premium) based on your risk appetite ( a level of risk that you can comfortably take) without giving too much consideration to the movement of the underlying stock. The premium is the option price -- the same thing -- because premiums rise and fall based on the stock price, but at different rate of change called the delta. So you would use this price to set your stop loss on your options trades.

Let's say you bought the TSLA AUG $350 (strike) Call @ $9.00 (premium) and decided that you cannot afford to lose more than 25% on this trade. You would then set a stop loss at $6.75 which would ensure that if the Option contract declined to $6.75, it would be automatically sold and you wouldn't lose more than $2.25 on the trade.



To set this up, you would first place the following order:

Buy To Open 1 TSLA AUG 350.00 Call @ Limit 9.00

and then once you are filled, you would go ahead and place the stop order:

Sell To Close 1 TSLA AUG 350.00 Call @ Stop 6.75, Limit 6.05.

As you can see above, you first have to open the trade using a buy to open and then you would need to do a sell to close using similar instruction outlined below.

For the screen above, once you place a check mark on "stop limit" it opens up two input boxes for you to enter 6.75 and 6.05. Here is what it would look like on this particular interface:



Other screen interface may look different and have different configuration.

Note that different brokerage services have different order screen interface with different method and location of the stop loss section and some allows you to set stop loss simultaneously at the opening of the position. For others, you would need to do a two-step: first, buy to open and then once you are filled, you would go ahead and place the stop order.

For example, at TradeKing (now Ally Financial) you would need to do a two-step: after you completed the first step, you would go to your account space that lists your stocks and options holdings, and each holding contains your outstanding position on your stock or option and at the right column it contains a right arrow "=>" for that particular stock or option.

You click on that arrow to popup a menu that allows you to do many other things, and one of them is to trade or close out that particular stock or option.

To set a stop loss means that you are setting the price to close out your position to be triggered in the future. That's what that popup order menu pane is for -- for you to close out your position to be triggered when your price is met.

If you want to place a stop loss on that option (or stock for that matter), you would click the item "trade" on the popup menu pane and it will open a trade pane for you to trade that option while allowing you to place a stop loss on that trade.

Again, different brokerage service have different order screen interface and you may have to look around to find where they place the stop loss or trailing stop loss at. You can always ask the brokerage service representative for help if you need help placing stop loss on your stocks or options.

If you look closely at the bottom of the screen interface above you'll see a section called Advanced Orders which contains, well, advanced orders such as trailing stop loss and many other types of advanced orders. So look around in your particular screen interface to find trailing stop and many other advanced orders.

One important note: When you set your stop loss make sure to select the duration for either a Day Order in which your stop loss is active until the end of the trading day on the day you set your stop loss; or a GTC (good til cancel) in which your stop loss is active until you actually cancel it physically by hand.

A Few Words About "Stop Orders" vs "Limit Orders" vs "Stop Limit Orders"

These orders are very confusing if you're not using it on a regular basis. It will take some practice to get you full speed. For more, please refer to these tutorials: Stop-Limit Order for Stocks. Stop-Limit Order for Options. Stop Orders

A "Stop Order" tells the market maker that you want to sell your contract at $6.75 once that price is reached. Period. Notice that stop order contains only one price: $6.75.

The important thing to note is that, with a "stop order", once the set price is reached, the order becomes executable and can be filled at whatever the current market price is, which can give you a very bad fill in a fast moving market.

For instance, let's say the TSLA stock price is moving around wildly, and the Option Contracts are moving just as fast in response to high volume and volatility, and you place a stop order to get out of the AUG $350.00 Calls at $6.75.

What is likely to happen here is that as soon as the price gets to $6.75 your order becomes executable. However, if there are many orders at that price lined up before your own, there is a strong chance ( given that the market is moving fast) that your order will not be filled immediately. So a few seconds pass and you finally get filled at 5.10 because that is the current market price.

You have just lost an additional $1.65 on the contract. So, please note that even though your order becomes executable once the price is reached, it doesn't mean that it will be filled right away. It rarely ever will be.

With a stop order you are effectively telling the market maker "I want to sell this contract once the price reaches $6.75, even if I don't get filled immediately at that price, I just want to get out of the trade once $6.75 is hit". A stop order does not guarantee the best possible fill.

Limit Orders

If you look at the example order (method 1) above, I used "limit orders" on the trade entry for $9.00 to tell the market maker that I want to buy the option at a set price of up to $9 and no more. It can be executed at any price below $9 but not above it.

Limit Orders on closing out your position is the same as opening position as you'd just seen, but the price can be executed all the way down to the limit price whereas in opening position price can be executed all the way up to the limit [self-explanatory]. So Limit Orders basically tell the market maker that you want to sell your contract if/when it gets to $6.75.

Stop Limit Orders

If you look at the example order (method 1) above, I used "stop limit orders" on the exit (sell to close) which takes two prices: $6.75 and $6.05.

A stop Limit order is obviously a combination of both the limit and the stop order. With a stop limit order you are telling the market maker that "I want to sell this contract at $6.05, and no lower, once the $6.75 level is hit. But do not sell unless I can get $6.05" or better.

Remember that, as noted in the stop orders above, even though your order becomes executable once the price is reached, it doesn't mean that it will be filled right away. It rarely ever will be. So your closing order could be much, much, much lower than you wanted.

To prevent that from happening, you use stop limit orders to limit your closing price that you want to sell. If the $6.75 is hit, the market maker will make an attemp to close out your position in a timely manner, but if by the time the market maker gets to your order que and the price falls below the stop price of $6.05, the market maker won't go ahead and execute your order because you told them not to do so by placing a stop limit order.

Sometimes you don't want to sell your holding if the price is too low to make sense in closing out your position and stop limit order allows you to accomplish that.

Trailing Stop Loss Orders on Options

So far we've only talked about the regular stop loss orders on options, the trailing stop loss on options is a lot simplier than regular stop loss, especially on existing holdings--holdings that don't have stop loss/trailing stop loss on them.

Here is a summary of trailing stop loss on options on existing holdings in visual screen interface views to help you understand better:



As you can see from this particular brokerage's screen interface, they placed the trailing stop order item in the advanced orders section. Your brokerage screen interface may place it somewhere else, so look around. Once you click on the trailing stop options in the drop-down menu, it opens up a screen that looks like the following:



As you can see from the screen above, at the top there are five headings: Symbol, Action, Contracts, Price, Duration. Most of them are self-explanatory, but under symbol, it shows an option contract for a Facebook Call option at $170 strike expires on June 19, 2020. This screen propagated from the previous screen and the previous screen resulted from the other previous instruction where you navigate to your options holding and click on a popup menu and click on "trade" to place a stop-loss on your options. So you don't have to enter anything on this section.

As a matter of fact, you don't even have to enter any of the items on the five headings. The only items that you need to enter are items on "Trailing Stop Criteria" section below it. Again, most of them are self-explanatory.

Point increment or price increment is the value of the trailing margin or gap you want the trailing number to trail the actual option price. If you set it to 5 (using price/points instead of percentage) it will trail the actual option price 5 points below the actual option price using bid price. If you set to 2% (using percentage instead of point) it will trail the actual option price by 2% using bid price. You can also use ask price by selecting the ask price from the drop-down list but most traders use bid price.

One important note: When you set your stop loss make sure to select the duration for either a Day Order in which your stop loss is active until the end of the trading day on the day you set your stop loss; or a GTC (good til cancel) in which your stop loss is active until you actually cancel it physically by hand.



The above screen shows the detail from the previous action from the previous screen entry.



The above screen shows the outstanding order status that you have placed.

In this screen, I want to point out one key point that I mentioned in an earlier example when I said '...you would go to your account space that lists your stocks and options holdings, and each holding contains your outstanding position on your stock or option and at the right column it contains a right arrow "=>" for that particular stock or option.

You click on that arrow to popup a menu that allows you to do many other things, and one of them is to trade or close out that particular stock or option....'


If you look closely at the far right end of the screen you'll see some sort of marking inside the circle. That circle is the one the arrow was pointing to when you navigate to your account holding space. So click on that circle to popup a trading menu. Follow the menu after that.

Method 2: Setting A Stop Order based on the underlying stock and the Option Greeks

This method is mostly often used by swing traders (particularly, experienced swing daytraders). For beginners in options, be advised to use the first method above. Note that this step uses the stock price to set the stop loss on your options positions instead of using option prices as in method 1.

This method comprises of a few steps but it is really very simple and can be very effective if executed properly. Let's take the same stock (TSLA) and Option contract ( AUG 80.00 Call) as an example and apply the following steps.

You want to take a look at the stock and see where it is trading relative to its nearest support level. In this case, TSLA closed the last session at 327.78 and the next level of significant support is at 315.25 and the next significant level below that is at 303.10.

Since we are swing trading, we have to assume ( and make room for) the possibility of a test of support. By setting our stops based on these support levels, we are ensuring that we will be out of the trade in the event that support is broken and the stock enters a downtrend.

How To Set A Stop For Options Trades

  • Since we now know that the next level of significant support is about $12.53 [$327.78 -- $315.25] from the current price we can go ahead and calculate an appropriate stop loss by using the Option Greeks.

    NOTE: For those who do not know, the Greeks are nothing more than a couple of metrics/numbers that are used to price and gauge the risk profile an option. Don't be intimidated by them. For our purposes, we are primarily concerned with the Delta. The Delta is basically the rate at which an Option will change based on the change in the stock price and it is usually stated as a percentage.

    For instance, if a call option has a .50 Delta it basically means that for every 1.00 move in the price of the stock, the option will rise by .50 (theoretically). This tutorial/guide is not for beginners so I am assuming you already know the basics. If not, you might want to check out a book called Trading Options Greeks which is by far the best book on Options trading.

    For most brokerage services interface, you should be able to find this Greek easily by looking around in the options chain. Here is what it looks like for this particular screen interface.

As you can see, under the Delta heading on the left side for call options starting at the top listing and run down the list for all the options. If you look at the top call option and run across to the right to the put option you'll see the delta number 0.671 (or 0.67 for our calculation purpose) for the call option and -0.331 (or 0.33) the delta number for the put option. Notice that the put option delta is negative -- all put options deltas will always be negative numbers since the deltas are going down.

  • Now a quick look at the contract profile for the TSLA AUG 350.00 calls reveals that the Delta is currently .35. So this means, in theory, that for every 1.00 move in TSLA, the contract should move by .35 cents. At this point, I have to remind you that time decay will also have an impact on how the option contract responds to movement in the stock price. So be mindful of that. But for this exercise, we will assume that only the Delta is important.

  • Now that we know that the Delta is .35 and we know that the next support level is at $315.25 we can do some calculations and get closer to an appropriate stop loss level for our trade. So, since we have decided that we want to get out of the trade on a break below the $315.25 level, we are basically saying we are willing to give up/risk $12.53 [$327.78 - $315.25] (or 3.81%) per share on the trade. With a delta of .35 that would be $4.38 [$12.53 * 0.35] on the AUG 350.00 Contract which is now trading at $9.00. Therefore, the stop loss will be set at $4.62 [$9 - $4.38] initially.
Of course, this would mean a 48.5% loss if you got stopped out but, once again, we are just using this as an example for this tutorial. Besides, you would be expected to adjust your stop loss upwards to lock in gains along the way.

Notice that we use the margin (or difference) bewteen the resistance/support levels and the actual stock price to further calculate the actual stop loss value.

A summary of the steps for method 2

Step 1: Find out where the significant support level is on the underlying stock you are trading and select an Option contract. The support level on TSLA was 315.25 and we decided we were trading the AUG 350.00 Calls which cost 9.00.

Step 2: Find out what is the Delta for the option contract you are trading. In our example, the Delta was .35.

Step 3: Subtract the price at the support level from the current stock price. eg. 327.78 - 315.25 = 12.53.

Step 4: Multiply the Delta by the result (amount of points/dollars) that you got from the subtraction in step 3. eg. 12.53 x .35 = 4.38.

Step 5: Subtract the result in step 4 above from the current option contract price. eg. 9.00 - 4.38 = 4.62.

Step 6: The result of the Subtraction in Step 5 above is where your stop loss on the Option Contract should be set. Finished.

How to Set a Stop Loss on Put Options

So far we've just talked about a call option, but what about the put options, how do we set stops on put options?

We follow the same steps as calls but only modify two steps: step 1 and step 2.

Step 1: Find out where the significant resistance level is on the underlying stock you are trading and select an Option contract. Remember that we're betting the option is going down, so if the option is going up against us we set the stop to get out. So we need to find the significant resistance level and assuming it is at 345 on TSLA Put at a cost of 12.00 (premium), we subtract the current price of 327.78 from the resistance level of 345, which is 17.22.

Step 2: Find out what is the Delta for the put option contract you are trading. The Delta for put options is negative.

So step 4 result should turn out to be a negative number.

And step 5 should have two negative signs: 12 - (negative step 4).

High school basic math tells us that we need to add them up and change the result as a positive number.

Next (step 6), use this positive sum as your stop loss. Your stop loss should be higher than the option premium because we want to protect our catastrophic loss if the put option heads toward the resistance and breaks through the resistance level to the upside. Done!

By using the movement of the underlying stock and the Delta value of the option contract, you are putting your self in a better position to manage the trade as opposed to just setting a random % risk level on the Option Contract by itself ( as in Method 1).

This second method is not for everyone and it works best for larger accounts and real swing trading ( 1 week minimum holding period) and it works best in strong trending markets. Let me repeat: this method will work much better if you are buying calls in a strong upward trend or puts in a strong downward trend.

Trailing Stop Loss Orders on Options

So far we've only talked about the regular stop loss orders on options for method 2, the trailing stop loss on options for method 2 is a lot simplier than regular stop loss you had to go through in method 2. In trailing stop loss, you don't have to worry about the delta and other messy calculations; you only have to come up with the trailing margin value, say, $5, in points to trail the option price movement and that is it! It will automatically trails the actual option price (premium) movement. Very simple!


What is a Relative Strength Index?

A Relative Strength Index or RSI is a momentum indicator that measures the magnitude of recent price changes to analyze overbought or oversold conditions. It is primarily used to attempt to identify overbought or oversold conditions in the trading of an asset.

The relative strength index (RSI) is calculated using the following formula:

RSI = 100 - 100 / (1 + RS)

To solve the equation using the above formula, we need to simplify the formula first because the two terms have different denominator. We need to find a common denominator and then we can solve the equation by plugging in the necessary value.

To simplify the above formula, we need to find the common denominator and then work out the math as usual, and that is all that we need to do. For example, the simplied formula process would looks something like this:

Finding the common denominator by multiplying the left side by (1 + RS)/(1 + RS):

RSI = [100 * ((1 + RS) / (1 + RS))] - [100 / (1 + RS)]

Multiplying the nominator [100 * (1 + RS)] out and the result becomes:

RSI = [(100 + 100RS) / (1 + RS)] - [100 / (1 + RS)]

Now we have a common denominator of (1 + RS) and the result becomes:

RSI = (100 + 100RS - 100) / (1 + RS)

Now we can go ahead and work out the math for the nominator as usual [100 - 100 = 0] and the result becomes:

RSI = 100RS / (1 + RS)

That is the final simplified formula.

As you can see, to calculate the RSI using the above formula -- specifically, the simplied formula -- we first need to calculate the Relative Strength or RS. Once we have the RS we can easily calculate the RSI.

To calculate the RS, we need to calculate the average gain of an underlining during a specified timeframe and also we need to calculate the average loss of an underlining during that same specified timeframe.

In other words, we need to calculate the average closing prices of a stock (or other underlining) that were up during the specified timeframe and also we need to calculate the average closing prices that were down during that same specified timeframe.

So we find the average closing price of an underlining that went up during a certain timeframe and also we find the average closing price of an underlining that went down during that same timeframe.

For example, if the timeframe is for 30 trading days and 20 of those trading days were up and 10 of those 30 trading days were down, we can calculate the average gain of up periods during that 30 trading days timeframe as:

Add all the 20 closing prices that went up and divide them by 20. Now we got the average gain.

And also we can calculate the average loss of down closing prices during that 30 trading days timeframe as:

Add all the 10 closing prices that went down and divide them by 10. Now we got the average loss.

Once you have the average gain and the average loss, you can find the RS by dividing the average gain by average loss. Here is the RS formula:

RS = Average gain of up periods during the specified timeframe / Average loss of down periods during the specified timeframe.

Once you have the RS, you can plug that RS value in the RSI formula shown earlier.

The RSI provides a relative evaluation of the strength of a security's recent price performance, thus making it a momentum indicator. RSI values range from 0 to 100. The default timeframe for comparing up periods to down periods is 14, as in 14 trading days.

Traditional interpretation and usage of the RSI is that RSI values of 70 or above indicate that a security is becoming overbought or overvalued, and, therefore, may be primed for a trend reversal or corrective pullback in price. An RSI reading of 30 or below is commonly interpreted as indicating an oversold or undervalued condition that may signal a trend change or corrective price reversal to the upside.

RSI is a very powerful indicator to use to indicate a trading pattern. As you might know, stocks rarely go up or down in a straight line; meaning, stocks move up to the resistance level and fall back to the support level and then move up back again to the resistance level and then back down again to the support level, repeating and bouncing like a ball in a container. Most of the stocks behave in this pattern for awhile before breaking out to either extremes [higher than resistance level or lower than the support level].

Once the stocks break out pass these resistance/support levels, the RSI becomes your powerful tool to use to indicate overbought/oversold territories.


Foreign Reserve

A foreign reserve is the foreign currency that a country has in its possession or in its bank vault. Remember that a country typically has its own currency, e.g., the United States has the dollar as its own currency, Great Britain has its own currency called the Pound, China has its own currency called the Yuan, Japan has its own currency called the Yen, the 12 European countries: France, Germany, Italy, etc., have their own currency called the Euro dollar.

For the most part, each currency can be used inside its own country only; for example, the Chinese Yuan can be used only inside China, and likewise, the European Euro dollar can be used only inside the 12 European countries and nowhere else.

When people travel to a foreign country, they have to exchange their own country's currency with of that foreign country's currency.

For example, if you go to China, once you arrived at the Chinese airport you need to change your U.S. dollar with the Chinese Yuan so that you can use it to buy things while you're in China. When you go to France (or any one of the 12 European countries that carry the Euro dollar), you need to exchange your U.S. dollar with the Euro dollar so that you can use it to buy things in those countries.

Likewise, when businesses invest or trade with a foreign country, they have to exchange their own country's currency with of that foreign country's currency.

For example, when Walmart Corporation buys Chinese products to sell in their stores in the U.S., they need to exchange their U.S. dollar with the Chinese Yuan so that they can use the Chinese Yuan to buy those Chinese products because the Chinese government barred the use of foreign currencies inside China.

Most countries do this as well, e.g., you can't use the Euro dollar to buy things in the United States either.

This exchanging of currencies is called the foreign exchange market.

Trades are the main source of the foreign exchange market (i.e., Walmart buying Chinese goods), causing each country's currency to fluctuate (or rise/fall in value) according to the supply and demand of the currency.

For example, the U.S. dollar is typically in high demand by traders all over the world and therefore it is more valuable than other currencies.

Keep the supply/demand principle in mind when you deal with the foreign exchange market, because it is based on the supply and demand of the currencies involved in the trade or exchange.

This trading of currencies in the foreign exchange market is where countries are so worried/abcessed with the concept of foreign reserve--they have to!. Their economy depends on it!

Now we're on to the description of the foreign reserve concept.

I'm little lazy, so I'm going to refer you to some excellent tutorials on the Web, which can explain better than I can.

As you watch the following videos, keep the trading of currencies in the foreign exchange market in mind because it is all about trading of currencies.

Also, don't forget to keep the supply/demand principle in mind as well.

To understand the concept of foreign reserve, you have to at least finished watching the third video in the list below. The first two videos are just the introduction to warm you up for the concept of the foreign reserve. Here are the video tutorials:

introduction

video 2

video 3

video 4


Ex-Dividend Date

When a company declares a dividend, it sets a record date when an investor must be on the company's books as a shareholder in order to receive the dividend. Once the company sets the record date, the stock exchanges or the National Association of Securities Dealers, Inc. set or fix the date set by the company and called it as "ex-dividend date." The ex-dividend date is normally set for stocks two business days before the record date.

So there are two dates to be considered here:

  1. Record date: the deadline date the company sets on its books for investors to be on to qualify for the dividend.


  2. Ex-dividend date: the date the stock exchanges or the National Association of Securities Dealers, Inc. set to two days prior to the record date set by the company. So the "ex-" (in theory) stands for extra--as in extra or in addition to the company's date.
So why there are two dates?

Well, because the stock exchanges and/or the National Association of Securities Dealers, Inc. cannot clear their books in time to meet the deadline set by the company, so the the stock exchanges and/or the National Association of Securities Dealers, Inc. set a new date to give them the time needed to settle trading transactions and clear their books.

So you have to pay close attention to two dates if you want to qualify for dividend. The most important date is the date set by the stock exchanges, although the date set by the company also somewhat important; however, pay close attention to the date set by the stock exchanges since it back-stepped the date set by the company by two days.

You get the dividend if you purchased a stock before the ex-dividend date -- the date set by the stock exchanges. If you purchased the stock on its ex-dividend date or after, you will not receive the next dividend payment. Instead, it is the seller who gets the dividend. So it is very important that you pay close attention to the date set by the stock exchanges.

What is a bond?

A bond is a loan that companies borrow to be used to fund the company's operation. A bond is simply an IOU -- a debt security or a promisory note that promises to pay back the principal along with the periodic interest payments. Bonds are issued by corporations, governments, and some times individuals (like rock singers Sting and Rod Stewart and Mick Jagger, etc). The most typical issuers of bonds are companies and governments. Individuals who issue bonds are rare.

When firms need cash to run its operations, they can either sell stock in the form of IPO or in the form of secondary offerings. But selling more stocks to the general public means that creating more supplies in the market, and, therefore, diluting current shareholders' value. That might not be the best case scenario for a company.

A better alternative is to issue bonds to raise cash. If a firm needs small amount of cash, it usually issues promisory notes or mortgages backed by the firm's real estate properties or other assets. When it needs larger amounts -- usually millions of dollars -- it needs to borrow from the general public by issuing bonds.

When goverments need cash to build bridges, sewages, schools, repair roads, and provide other essential services to the general public, it needs to borrow from the general public by issuing bonds.

When companies or goverments need to raise cash, they will offer the general public a deal. It's called floating an issue. In essence, floating an issue is another way of testing the market to see if the bond is appealing to investors at an acceptable interest rate.

A common expression for testing something in the market (particularly bonds) is: "Let's see if it floats." Thus, floating an issue. In other words, let's test to see how receptive our bonds are before we issue the bonds. If the bonds have a high enough rating and high enough percentage offerings, the chance of those bonds will float is high.

So bond issuers usually advertise their float first to see if their bonds will float and then once they receive enough inquiry from prospective bonds buyers, then they decide to issue the bonds and sell to the public. If the bonds are not well-received, then they might scrap the offerings and do another test float by raising the interest rate on the bonds and/or collaterize the bonds with more assets to calm investors' nerve.

When you buy stocks, you gain equity in the company and become a part-owner. When you buy bonds, you own debt in the company and become a creditor to the company because you have loaned money to the company or government (or individual).

Investors lend money to corporations and governments to earn interest on the money that they loaned. The bond is just a piece of paper called a bond certificate that signifies that they had loaned the money to the corporation or government. In other words, investors that buy bonds become lenders and corporations and governments that sell bonds become borrowers.

As with most loans, the borrower pays interest to the lender. A bondholder usually receives regular interest payments from the issuer of the bonds. Unlike stock dividend payments, which change along with company profits levels, interest payments on a bond are usually fixed.

For example, a corporation or government may floating an issue in the open market for a bond that pays 8% annual interest over 15 years. This quarantees that the annual interest rate stays fixed for the whole life of the bond, which is 15 years.

The wording of the floating an issue over the electronic newswire looks similar (but not exactly) to this:

XYZ Corporation
XYZ Corporation is floating an issue of $20,000,000 in the open market for a bond that pays 8% annual interest over 15 years in denominations or units of $1,000.

What that means is that XYZ Corporation is announcing to the general investing public that it plans to offer to sell a bond worths a total of $20,000,000 that pays 8% annual interest rate over the life of the bond, which is 15 years, in increment of $1,000 lot.

If the general investing public likes the deal in a floating an issue, then they would inquire about the floating of the issue and offer to buy those denominations or units. Notice that you do not need to have hunreds of thousands or millions of dallors to buy a bond: you only need to have a minimum amount of the lot, usually $1000, to buy a bond.

If enough demands for the floating an issue, then the XYZ Corporation might go ahead and issues the bond. If not enough demands for the floating an issue, then the XYZ Corporation might cancel the floating of the issue and issues another floating issue with a higher annual interest rate to entice the general investing public to accept the deal.

Corporations usually offer in denominations or units of $1,000 lot. But, governments -- especially federal government -- issue some bonds in denominations or units of $1,000, $500, $250, $100, and $50. Again, you do not need to have hunreds of thousands or millions of dallors to buy a U.S. government bond: you only need to have a minimum amount of the lot, $50 in this case, to buy a bond.

Bond Certificates

When a corporation or government needs to issue a bond, it hires an investment banker that specializes in writing and handling bonds issue. An investment banker writes a bond indenture, or agreement, that shows in detail the terms of the bond -- such as annual interest rate and the life of the bond -- and the rights and duties of the borrower and other parties to the contract. [A bond indenture is an agreement or term]

Most bonds are issued with three essential pieces of information:

  • Interest Rate is the percentage rate of Par Value that will be paid in interest to the bondholder on a regular basis. For example, this $1,000 bond would pay 12 3/8%, or $123.75 a year.

  • Maturity indicates when the term of the loan expires ("is due") and the bond will be retired ("paid off" in full).

  • Par Value is the amount the bondholder will be repaid when the loan is over. Usually, par value is $1,000. A Baby Bond is a bond with a par value of less than $1,000. Governments -- especially federal government -- usually issue Baby Bonds in par value (denominations or units) of $500, $250, $100, and $50.

Who Issue Bonds?

Only corporations can issue stocks, but bonds can be issued by corporations or governments or individuals.

The most typical governments that issue bonds are:

  • Federal governments. The U.S. Federal government always issue bonds to pay for a wide range of federal government activities: defense spending, war costs, catastrophic events (hurricans, floods, eartquakes, etc), infrastructures, federal aid to states, and so forth.

  • Federal government agencies. Bonds issued by federal government agencies are indirect obligations of the U.S. government. Some of the most well-known are the U.S. Postal Service, which borrows heavily to fund its operation; FANNIE MAE, FREDDIE MAC, GINNIE MAE, FHA, and the Tennessee Valley Authority.

  • Municipal governments. States, cities, counties, and towns issue bonds to pay for a wide range of publicly beneficial projects: schools, roads, sewage systems, other infrastructures (bridges, camp/play ground), stadiums, and so forth.

  • Foreign governments. Many foreign governments issue bonds specifically to U.S. investors. Just like U.S. governments, foreign governments also issue bonds to pay for a wide range of publicly beneficial projects and other essential services.

  • (U.S. and Foreign) Corporations. For corporations, bonds are a primary way of raising cash to fund its operations. The money raised pays for expansion, modernization, acquisitions, and other expenses.
For investors, the beauty of bonds is steady income. When you invest in a bond, you can expect to receive regular, fixed interest payments for as long as you hold the bond -- unless the issuer goes broke.

You may hear a bond's interest referred to as coupon. That's because some bond certificates come with detachable slips similar to car payment slips. The detachable slips contain the bond's interest payment schedule and other information pertaining to the bond. With these coupons or slips, you can actually clip a coupon and send it in the appropriate time to receive your interest payment. That was in the old days before the electronic age caught a storm. Nowaday, everything is done electronically and investors don't have to do anything, but the use of the term coupons still exists.

Bonds are backed by the full faith of the issuer. If the issuer of the bond pledges property as collateral for the loan (as in a mortgage bond), the bond indenture or term names a trustee or agent to hold the title to the property serving as collateral. The trustee acts as the representative of the bondholders and is usually a bank or trustee company.

The issuer of the bond (borrower) or trustee appoints an agent (usually a bank or trustee company) to act as registrar and disbursing agent. When it comes to making payments, the issuer of the bond deposits interest and principal payments with the disbursing agent, who distributes the funds to the bondholders.

To provide some protections to bondholders, bond indentures typically limit the bond issuer's right to declare dividends and make other distributions to company's shareholders. Well, if you're a bond buyer you don't want the bond issuer to spend money wildly that can cause the company to default on your bonds. It makes a lot of sense.

What Is a Bond Worth?

All bonds carry a fixed interest rate. But interest rate in the market usually fluctuates according to market conditions. Bond prices also do fluctuate according to market condition. For example, a corporation issues a bond that has a value (or price) called par value of $1,000 that pays 8% annual interest rate for 5 years.

During the life of the bond, which is five years, the interest rate in the market may fluctuate up or down more or less than 8% in one month, two months, three months, two quarters, three quarters, or one or more years.

All those scenarios could happens while the interest rate on that bond is staying fixed at 8% annual interest rate during the life of the bond.

Changes in interest rates, such as when the Fed raises or lowers its Fed Funds rate, effect the prices of the bonds. Issuers of the bonds often offer to pay investors (bondholders) a rate of interest which is competitive with other bond rates at the time. As a result, the rate on a new issued bond is usually similar to other interest rates: prime rate, mortgage rates, personal loan rates, etc.

After a bond is issued, however, interest rates in the economy may change -- making the rate on the (old) issued bond (which can't change) more or less favorable to investors. If the (old) issued bond is paying more interest than the generally available elsewhere, investors will be willing to pay more to own it. On the other hand, if the (old) bond is paying less interest than the generally available elsewhere, investors will not be willing to pay more to own it. They can go somewhere else to get a better deal.

Originally, bonds were not meant to be traded on the open market as a secondary market. Bonds were intended to be sold by the issuers--and not by the freewheeling investors.

As often the case, the law of economics prevails. The higher the yield on the bond the more people wanting to buy the bond from a secondary market. As the interest rate fluctuates, the bonds become favorable or non-favorable for the original bondholders, creating a secondary market for the (old) issued bonds.

In general, consequently, interest rates and bond prices fluctuate like two sides of a seesaw -- when one side move the other react in opposite. This is the law of economics at work. When interest rates drop, the value of existing bonds become favorable for investors because the rates on new issued bonds are usually similar to other interest rates: prime rate, mortgage rates, personal loan rates, etc.

If existing bonds become favorable for investors, in other words, if the existing bonds become such a high demand, investors would bid up the prices of existing bonds, making the prices of the existing bonds go higher than its par value. When interest rates rise, the reverse is also true.

Let's say, for example, that XYZ Corporation floats a new issue of bonds offering 6 3/4% interest. You--the bond buyer -- decide this is a good rate compared to what else you could invest in. So you buy some bonds at full price (par value), $1,000 per bond.

Now three years later, interest rates in general are up. If new bonds costing $1,000 are paying 8% interest, no buyer is going to pay you $1,000 for your 6 3/4% XYZ bond. To sell, you'll have to offer your bonds at a discount to induce buyers to buy your bonds that are carrying lower than the going rate.

Of course, you can hold your bonds to maturity and keep receiving a 6 3/4% interest throught the life of your bonds. But as an investor, that doesn't make any sense tying your money to receive almost two percent lower that you could if you hold new bonds. So a prudent thing to do is to sell your bonds at a discount and replace them with higher interest bonds.

Now consider the reverse situation. If new bonds selling for $1,000 offer only a 5 1/2% interest rate, you'll be able to sell your 6 3/4% XYZ bonds for more than what you'd paid--say, you could sell them for $1,200 per bond -- since buyers will be willing to pay a premium to obtain your higher interest rate bonds.

A side note: In the financial jargon, you will often hear people mention the terms discount or at a discount and premium or at a premium quite a lot. A discount is to buy/sell something (usually stocks or bonds) less than the original price. A premium is to buy/sell more than the original price.

A bond contains value to investors. Two factors usually determine a bond's value:

  • Yield. How much you'll earn from interest payments compared to what you could earn from other investments. The higher the yield on your bond the more money you earn, and also the more people wanting to buy your bond from you. Bonds are tradeable securities.

    A bond's yield is not the same as its interest rate. The term yield describes what you'll actually earn from a bond, based on a simple calculation. Investors determine bond values largely by comparing yields.

    Dividing the amount of money a bond will pay in interest by the price of the bond gives you a bond's yield. For example, if a bond value (or price) is $1,000 that pays 8% annual interest rate for 5 years, so $80 / $1,000, youll receive $80 a year from this bond. It would yield 8% on that bond. In this case, a bond's yield is the same as its interest rate.

    If, however, a year later, the bond loses value and it's sold in the secondary market for $800, the new buyer would still receive the $80 a year in interest payments from the bond issuer. Remember that the par value of that bond is still $1,000, but the same bond is sold for only $800 in the secondary market, a difference yield of 2.1% per year.

    Now the $200 difference yields a 2.1% per year (200/800)/12. You hold the bond only for 4 years, and therefore, the total percentage return on that is 8.4% (2.1 X 4).

    Now that was just the return on the $800 investment principal. What about the interest payments for four years? Don't they get counted as return on investment?

    The correct answer is, "Yes, they all get counted as return on investment." So, since the bond was sold for only $800 the yield for interest payment for each of the four year is 10% (80/800). Add the two yields (2.1% + 10%) together and you would get 12.1%. The new buyer would receive a 12.1% return on investment (or yield).

    As you can see, a bond's yield is not the same as its interest rate. The interest rate for the bond is 8% while the yield for that bond is 12.1%.

    On the other hand, should the bond be sold in the secondary market -- a year later -- for a premium, say $1200, the new buyer would still receive the $80 a year in interest payments from the bond issuer. Remember that the par value of the bond is still $1,000, but the same bond is sold for a premium at $1,200 in the secondary market. This means that when the same bond is due, you will get only $1,000 (not $1,200).

    Now the $200 difference yield a negative of 2.1% per year (200/800)/12. Meaning that your return on your investment is 2.1% lower than you would have gotton had the same bond had been sold for the same amount of $1,000 in the secondary market. You hold the bond only for 4 years, and therefore, the total percentage return (or yield) on that $200 is 8.4% lower (-2.1 X 4).

    Now that was just the return (or yield) on the $1,200 investment principal. What about the interest payments for four years? Don't they get counted as return on investment?

    The correct answer is: yes, they all get counted as return on investment. So, since the bond was sold for $1200 in the secondary market, the yield for interest payment for each of the four year is 6.67% (80/1200). Add the two yields (-2.1% + 6.67%) together and you would get 4.67%. The new buyer would receive a 4.67% return on investment (or yield).

    As you can see, a bond's yield is not the same as its interest rate. The interest rate for the bond is 8% while the yield for that bond is only 4.67%.

  • Safety. How safe is your bond? In other words, how sure are you that the issuer will repay the loan when it comes due? High safetyness also attracts other investors wanting to buy your bond from you.
What Is a Yield To Maturity?

A yield to maturity is a more precise measurement of bond value. The figure takes into account is the interest rate in relation to the price; the purchase price versus the par value; and the number of years left until maturity. So, if the par value of a bond is $200 more than you paid, that eventual profit will be added to your interest in calculating the yield to maturity.

Yield to maturity isn't easy to calculate and you almost need to be a PhD in mathematics to be able to calculate the yield to maturity. It's computed according to a complicated mathematical formula that is beyond my scope of expertise. Nevertheless, you should know a bond's yield to maturity before you make a decision to buy. Your broker can provide you with this information.

The Jargon of Bonds

The jargon of bonds (or language/terminology of bonds) can be hard to understand if you're not familiar with some common bond features and terminology. Bonds have many names and types. Bills, notes (senior notes), T-Notes (Treasury Notes), promisory notes, T-Bills (Treasury Bills), zero-coupon, debenture, etc., are all bonds.

All bonds are IOUs or debts that are generally issued by governments or corporations. Bonds differ according to their maturity period -- the length of time until they become due. Bills mature in one year or less. Notes in 1-10 years, and bonds in over 10 years.

Municipalities and corporations only issue notes, bonds, and debenture, but never Bills. Bills are only issued by the U.S. Federal government.

For investment safeguard, investors often turn to T-Bills (Treasury Bills) for their investment. T-Bills are the safest in the world -- because they are backed by the U.S. government. But T-Bills are often offer you little return on investment.

During times of volatile interest rates, investors often turn to T-Bills with their short maturities to avoid being locked into a rate for a long time.

Debenture Bonds

Another form of bonds is called debenture (de`ben`cher). Debenture has a simple meaning. It refers to any bond which is backed by only the good credit (credit worthyness) of the organization issuing it. The term debenture means an unsecured loan certificate issued by a company, backed by general credit rather than by specified assets. So debenture bonds are bonds that have good credit worthyness.

In other words, the issuer doesn't put up any specific collateral assets to assure repayment of the loan. As a bond buyer, you rely on the issuer's full faith and credit (credit worthyness) as your only assurance of being paid the interest and principal on your loan.

This isn't as risky as it may seem. When issued by reliable institutions, debentures are usually relatively safe investments.

Subordinated Bonds

Another form of bonds is called subordinated bond.

Remember, buying a bond makes you a money lender to the organization issuing the bond. You are a creditor--they owed you money and they must pay you back the money that you lend to them. You and other lenders -- individuals and institutions -- have equal rights to receive the repayments of the loan should the organization issuing the bonds default on the loan or go out of business.

The assets of the organization issuing the bonds are usually liquidated and the proceeds are divided up among the creditors -- you and other lenders (individuals and institutions).

When you buy a subordinated bond makes you a subordinated money lender to the organization issuing the subordinated bond. You are a subordinated creditor, and you receive the repayments of the loan after other creditors got theirs -- should the organization issuing the bonds default on the loan or go out of business.

The organization issuing the subordinated bonds is obligated to pay its debts to some other creditors -- such as non-subordinated bondholders -- first before paying you. Your rights are subordinated to the rights of some others.

Asset-Backed Bonds

Another form of bonds is called asset-backed bond. Asset-backed bonds are bonds that are backed by specific assets. The organization issuing the asset-backed bonds pledges specific assets as collateral for the bonds. The most common asset-backed bonds are mortgage-backed bonds.

For these asset-backed bonds, the issuer promises to mortgage properties, if necessary, to repay the loan. Other kinds of asset-backed bonds are bonds backed by equipments or collateral trusts -- security holdings (usually stock holdings) from other institutions.

Floating-Rate Bonds

Another form of bonds is called floating-rate bond. Usually, a bond carries a fixed interest rate throughout its life. Floating-rate bonds are bonds that are periodically adjusted to reflect the fluctuation of the interest rates. This is similar to an adjustable rate mortgage (or ARM) for homeowners holding an adjustable rate mortgage for their homes.

Zero-Coupon Bonds

Another form of bonds is called zero-coupon bond. Most bonds pay out regular interval interest payments. In bond jargon, the term coupon means interest. Zero-coupon means zero interest (or no interest). Therefore, zero-coupon bonds are bonds that pay no interest while the loan is still outstanding. Instead, interest accrues (builds up) and is paid all at once at maturity.

You buy zero-coupon bonds at prices far lower than par value, called deep discounts. Any time the bonds are selling far lower than their par value, say $800 of the bond that has a par value of $1,000, people rush to buy the bonds in droves.

When the bond matures, you receive all the accrued interest plus your original investment called capital, which together add up to the bond's par value. This means that if you buy a bond that has a par value of $1,000 (not necessarily that you paid $1,000), you will get your full payment (accrued interest plus your original investment called capital) in the amount of $1,000--not more.

Callable Bonds

Another form of bonds is called callable bond. Many bonds come with a string attached: the issuer may call (recall or retire) the bonds -- pay off the debts -- any time after a certain number of years, usually after five years into the life of the bond, but not before that.

It's the same idea as refinancing your house to get a lower interest rate and make low monthly payments. This process is called redemption -- redeeming the callable bonds. If only some of the bonds of a specific issue are to be redeemed, those to be called are chosen by lottery.

US Savings Bonds

Another form of bonds is called US Savings bond. Unlike the other kinds of bonds discussed thus far, US Savings bonds are not marketable (tradeable) in the secondary market. They can be bought only from the US government and cannot be traded among investors in the open market.

So US Savings bonds are somewhere between the an investment and a savings instrument -- but they remain an important and popular choice for millions of individual Americans.

In one way, US Savings bonds are the original zero-coupon bonds: you buy them at a discount from par value and, upon maturity, the government pays you the full face value.

For example, if you'd ever bought a $50 US Savings bond as a wedding or other gifts, you might recall paying about $37.50 for it. During the 10-year maturity period, the government paid no interest on that US Savings bond that you bought; however, the person whoever received the gift was able to redeem it for $50 upon maturity.

Actually, the government paid interest on all US Savings bonds, but the interest is factored in the US Savings bond when you bought it.

Convertible Bonds

Another form of bonds is called convertible bond. When you buy a convertible bond, you receive regular interval interest payments just like any other bond. But the difference between a convertible bond and a regular bond is that a convertible bond gives you the option to convert your bond into company stock as repayment of the loan principal instead of cash.

The terms of conversion is alway specified at the time you buy a convertible bond. Make sure to read the terms of conversion before making a decision to buy.

You might ask, "Why not take the cash and use that cash to buy the same stock?" After all, the stock costs you cash (any way you look at it).

But wait, the caveate is in the terms of conversion. The terms of conversion specifies when you'll be allowed to make the conversion -- usually after a couple of years into the life of the bond -- and how much stock each bond can be exchanged for.

The most caveate of all is in the 'how much stock each bond can be exchanged for,' since the price of stock fluctuates -- allowing you to determine whether it is a good investment to convert or not to convert. This is similar to a stock option where a set price called strike price is specified at the time of the granting of the option. Similarly, the price of the stock is specified at the time you buy a convertible bond.

After a couple of years into the life of the bond, the stock price may fluctuate way up, making a conversion seems a good investment. Note also that when you buy a convertible bond there is a chance that you can cash out your bond sooner than if you buy regular bonds.

For example, if you buy a convertible bond and two years into the life of the bond that has a 10-year maturity, you can convert that bond into company's stock and immediately sell your stock holding and realizing the profits instantly along with receiving your principal money in full in just two years [without having to wait 10 years to receive your principal money if you had bought a regular bond].

Yes, convertible bonds can be very profitable if condition is right, and most importantly, you don't have to tie up your principal money very long either if conversion scenario is in your favor.

Let's take a look at an example of Tesla Convertible bond in the amount of $920 million due March 1, 2019. Here is an excerpt of the term on the bonds that Tesla reported in its 2017 10-K filing with the SEC:

"Each $1,000 of principal of these notes is initially convertible into 2.7788 shares of our common stock, which is equivalent to an initial conversion price of $359.87 per share, subject to adjustment upon the occurrence of specified events. Holders of these notes may elect to convert on or after December 1, 2018...."

What it means is that bondholders can elect to receive its principal amount in Tesla's stock for $359.87 a share. If you divide $1,000 by $359.87 equals to 2.7788 shares of Tesla common stock. So each $1,000 of principal that bondholders have can be converted into 2.7788 shares of Tesla common stock.

Speculation on Tesla's Financial Woes:

The wide spread speculation on Wall Street is that Tesla is having huge problem with cash and several bonds are coming due quickly, one in November 2018 in the amount of $320 million (convertible), two on March 1, 2019 in the amount of $920 million (convertible), and as well a $180 million term loan comes due at the end of June, 2019, while about $566 million in convertible bonds mature in November 2019 and several in 2021 and beyond.

The $320 million (convertible) due in November 2018 was issued in October 2013 by it subsidiary SolarCity and carries a 2.75% convertible notes. Conversion price of $560.64 -- meaning -- Tesla stock has to trade at least $560.64 a share up to the due date in order for Tesla to be able to convert the $320 million bond into shares of Tesla. As of right now (August 10, 2018), it doesn't look like the stock will reach that convertible level. So most likely Tesla will have to come up with $320 million in cash to pay off the bond.

As with the $920 million due in March 2019 (March 1, 2019), it was issued by Tesla itself in March 2014 and carries a 0.25% convertible notes. Conversion price of $359.87 -- meaning -- Tesla stock has to trade at least $359.87 a share up to December 1, 2018, the earliest date the bond can be converted into stock. If the stock is not at $359.87 by December 1, 2018, the deadline for conversion is still March 1, 2019, if the stock can reach the coversion price. So both parties have until March 1, 2019, to execute the conversion in the event that stock price reaches the conversion level. Otherwise, Tesla will have to come up with the $920 million to pay off the bond.

One of the speculation is that Elon Musk was trying to drive up Tesla's stock price above $359.87 a share so that he doesn't have to use cash to pay back the bondholders in principal payments when he tweeed on August 7, 2018, that he has a plan to take Tesla private with a price tag of $420 per share. Initially Tesla's stock price jumped up to $380 a share but as investors realized that Musk's plan was not going to work, the stock dropped back to around $350 a share.

If Tesla's stock price is trading above $359.87 by December 1, 2018 -- the earliest date the bond can be converted into stock -- and possibly stays above $359.87 until March 1, 2019, the bondholders would most likely convert their bonds into shares of Tesla because it is more profitable than receiving cash for their principal investment. So the higher the stock price the more profitable the bondholders stand to benefit if they hold a convertible bond.

Note that the 2021 bonds are non-convertibles, where the principal is always repayable in cash, but the 2018 and 2019 convertibles may be redeemed wholly in shares (at Tesla's option and if the requisite conversion ratio has been met). So, it all looks very simple - if the share price goes above $359.87 by December, Tesla can escape the payment by issuing shares instead, but if the price is below, as currently seems likely at this writing August 10, 2018, Tesla will have to come up with the cash, right? Well, not exactly.....

Tesla can issue more stock to sell to the public and use that cash to pay off the bondholders. But having stock prices higher benefit Tesla because Tesla can sell less shares to earn more cash. On top of that, if Tesla's stock is higher than$359.87 Tesla doesn't have to issue more shares to sell -- they can just elect convert the bonds into shares of Tesla's stock.

So having Tesla's stock stay high has many benefits to Tesla and that's why Wall Street is speculating that Musk's motive was to drive up Tesla's stock when he tweeted about taking Tesla private.

Looking to add bonds to your portfolio?

How to Invest in Bonds: A Step-by-Step Guide

If you're looking to get started with bond investing, here's a step-by-step guide that will teach you everything you need to know.

  1. Understand the basics of how bonds work. To get yourself up to speed on how bonds work, familarize yourself in my other tutorial called "Introduction to Bonds."

  2. Decide which type of bonds to buy. Not all bonds are created equal. In fact, there are several types of bonds you might choose to buy:
    • Corporate bonds are those issued by companies to raise money for things like research and capital improvements. The interest you receive from corporate bonds is taxable at both the state and federal level.

    • Municipal bonds are those issued by cities, states, and other localities to finance public projects and increase public services. The interest you receive from municipal bonds is always tax-exempt at the federal level, and if you buy bonds issued by your home state, you can avoid state and local taxes as well.

    • Treasury bonds, or T-bonds, are those issued by the U.S. government. The interest you receive from T-bonds is taxable at the federal level, but exempt from state and local taxes.

    • Convertible bonds are bonds issued by publicly traded corporations. In other words, convertible bonds are bonds that can be converted into publicly traded stocks. Convertible bonds can be a very lucrative investment if you happen to find convertible bonds issued by explosive growth companies, because stocks of growth companies tend to grow explosively along the companies themselves. So make sure you do your due diligence on the companies and its future prospect and don't forget to read the bond's debenture or terms.

  3. Choose an investment horizon or maturity date. While you're not required to hold your bonds to maturity, if the value of your bonds falls after you buy them, you may have no choice but to retain them long term to avoid taking a hit on your principal investment.

    That's a big reason why you'll need to put some thought into your ultimate investment horizon. Because bonds come with differing terms (10 versus 20 versus 30 years, for example), setting some investment goals can help you determine how long to potentially lock your money away for.

    Remember that you can sell your bonds at any time and you don't have to hold them to maturity, but be aware that the price of your bonds may fluctuate according to market conditions.

  4. Research your investments. You'll often hear people making statements like these: "Bonds are a safe investment, and stocks aren't." But it's rarely that simple.

    While bonds are typically less volatile than stocks, choosing the wrong bonds could expose you to more risk than you may have bargained for. That's why it's important to look at bond ratings when choosing a company or municipality to invest in. The higher the rating, the less likely your issuer is to default on its obligations.

    On the flip side, bond investors tend to be rewarded for taking on more risk, so if you buy bonds from an issuer with a lower rating, you'll typically snag a higher interest rate.

    If you don't want to shoulder the risk of buying individual bonds, you could always invest in a bond fund instead, which gives you instant diversification. Think about it: If you buy bonds from a single issuer and that issuer defaults, you're out of luck. But if you buy a bunch of bonds and a single issuer defaults, you'll continue to make money from the rest of the bonds in that pool.

    The downside of bond funds, however, is that your income stream will be less predictable, as you won't get those same steady interest payments that holders of individual bonds collect. One of the reasons is that bond funds are actively managed by fund managers who buy/sell bonds the moment they feel the bonds are in/out of favor.

    In other words, like stock fund managers, bond fund managers buy/sell bonds actively and rarely hold their bonds to maturity.

    You can also check out the rating agencies such as Moody's Investors Service, Fitch Ratings, Standard and Poor Ratings, and learn their rating classification.

    No matter your age, bonds can play a big role in helping you meet your investment goals. Just make sure to weigh the pros or cons of bonds versus other instruments so that your choices align with your ultimate objectives.

  5. Just like investing in stocks, you don't need thousands or millions of dollars to invest in bonds. It can be as little as $50 to invest in individual bond. Just like in stock, in which, you have to have a minimum amount of money to buy a share worth of stock, in bonds, you have to have a minimum amount of money to buy a lot or unit worth of bond as well. Bonds are sold by the lot or unit just like stocks are sold by the share.

    Corpoate bonds are sold in lot or unit denomination of $1,000, which means that all you have to have is a $1,000 to buy any corporate bond.

    Goverment bonds (issued by the U.S. government or by municipalities like cities, states, and other localities) are sold in lot or unit denomination of $50, $100, $1,000, which means that all you have to have is $50 to buy any government bond.

  6. The best place to get your feet wet with bond investing is to signup a trading account with one of the brokerage services. Check out an instruction that I put out called "Get Started Trading Options." Once you have an account, you can trade stocks, bonds, options, mutual funds, etfs, etc.

    As always, if you have any question you can ask your brokerage representative on how to invest in bonds or any other investment (for that matter).

What is a yield curve and why is everybody talking about it so much?

Before I answer that, let's see the synopsis:

  • If you invest in equities, you should keep an eye on the bond market.

  • If you invest in real estate, you should keep an eye on the bond market.

  • If you invest in bonds (or bond ETFs), you should definitely keep an eye on the bond market!

So everything with yield curve has to do with bond yields -- and bond yields have to do with the economics principle supply and demand.

The higher the bond yield, the lower the demand for that bond. Likewise, the lower the bond yield, the higher the demand for that bond.

Say what? The higher the bond yield, the lower the demand for that bond? Does it make any sense?

Take it this way: When you see stores with advertisement that says something like 30% off, 40% off, 50% off, or 60% off, they're telling you that their products are not in high demand and to get rid of those products, they have to lower prices to entice customers to buy them.

Bonds work the same way: When there are lack of demand for the bonds, their yields are typically higher because seller(s) of those bonds will offer bond buyers with higher interest rates to entice bond buyers to buy those bonds; and therefore, making those bonds having higher yields. Make sense?

So the yield curve is the graph that plotted the bond yields. Economists use charts and graphs to interpret the activities of the economy and bond yields is a very important key that drives economic activities.

In the graph illustrated below shows the yield curve for the 10-year bonds, and it is not upward slopping, but rather, it is flattening, which means that the demand for 10-year bonds are in high demand, driving their yields down, hence the flattening of the yield curve. In other words, people are buying more 10-year bonds than they're buying 2-year bonds.

The bond market is a great predictor of future economic activity and future levels of inflation, both of which directly affect the price of everything from stocks and real estate to household items.

The yield curve is a curve on a graph in which the yield of fixed-interest securities (typically bond yields) is plotted against the length of time they have to run to maturity. So bond yields are used in the graph to plot the curve at various length of maturity. A yield curve is almost always upward sloping, a sign that the economy is functioning properly.

The bond yield curve has in the past been a signal of an impending recession. When the interest yield on the 10-year US Treasury bond becomes the same as the two-year bond, recessions have often followed. The "curve" is the line that plots the difference between them over time. Right now (year 2018) that line is trending toward zero, or flat. See the graph below:



As you can see, the graph should be sloping upward considering how well the economy is doing right now (2018). Is the downward sloping telling us there is an impending recession? There are both sides of this debate.

The horizontal line that has number 0 (zero) can be viewed as the benchmark 2-year bond yield (for easier interpretation). It is actually a line representing maturity dates, however. A 10-year bond is plotted against this horizontal zero-line with varying maturity periods.

If the plotted graph representing a 10-bond goes below zero -- an "inversion" in which the yield on the two-year bond would be greater than the 10-year -- that traditionally signals something is very wrong in the market.

Why?

Because a flat or negative yield curve suggests investors believe keeping your money in short-term bonds is more uncertain than bonds that pay off a decade from now. Think about it. That position doesn't make sense. Why would you be more certain about 2028 than 2020?

Thus, when the curve inverts or crosses the ten-year U.S. Treasury bonds yield, it signals something very risky is happening in the near-term asset markets.

To best understand the yield curve, put yourself in the shoes of the lender, the borrower, and the investor. Each entity is rational and looking to do what's best for their bottom line.

Lender's Perspective

Due to inflation, the value of a dollar tomorrow is worth less than the value of a dollar today. Therefore, in order to profitably lend money, you must charge an interest rate. The longer the lending term, the higher the interest you should charge, hence the upward slope of the yield curve.

Make note that the 10-year bonds should always have higher interest rate than the two-year bonds. But according to the graph above, the 10-year bonds yield curve is trending toward the two-year bonds yield curve. Something fishy is going on!

If the borrower has a poor credit score, runs an unstable business, has large job gaps in his resume, not well-versed in the financial market, or doesn't have many assets, then you need to charge an even higher rate to account for credit risk. If you can get a borrower to pay back an interest rate higher than your competition, you're making superior economic returns. That's the goal of the lenders.

If you are a bank, your main source of funding is from saving deposits. For the privilege of holding such deposits, you pay customers an interest rate and hope to lend out their deposits at a higher interest rate for a positive net interest margin. If the yield curve is upward sloping, banks have an easier time achieving such profitability as appose to the yield curve is trending in a downward sloping.

In other words, the upward slope of the yield curve tells us that banks are able to borrow and lend money at a profitable margin. If that is the case, banks would surely continue to borrow and lend, making the economy forging along ahead.

Besides using depositors money, banks borrow money from other sources as well at short-term rates (usually at very low interest rates) and turn around and lend it at higher interest rates for longer-term periods. The greater the difference between the two, the more profitable it is for banks to borrow and lend money. However, when this gap shrinks causing the yield curve to flatten, it becomes less enticing for banks to borrow and lend. And when the yield curve inverts, banks have virtually no desire to lend money, leading to a halt in growth and a recession.

Borrower's Perspective

A rational borrower is incentivized to:

  1. borrow as much money.

  2. for as long a period of time.

  3. at the lowest interest rate possible to get rich.

The more you borrow, the more you will likely invest. When the borrowing rate is equal to or below the inflation rate, a borrower is essentially getting a free loan.

The classic borrower example is the homebuyer. After putting down 20%, the buyer borrows the remaining 80%. The lower the interest rate, the more inclined the borrower is to take on more debt to buy a bigger, fancier house. When homebuyers want to stretch, they take out short-term adjustable rate mortgages (ARM) with lower interest rates versus 30-year fixed loans with higher rates. In a declining interest rate environment, taking out an ARM is an optimal move.

In addition to homebuyers, there are companies large and small, that borrow money to grow their businesses. If interest rates are lower at every duration, businesses will tend to borrow more, invest more, hire more, and consequently boost GDP growth.

Given the motivations of the borrower and the lender, the investor sees the yield curve as an economic indicator. The steeper the yield curve up to a point, the healthier the economy. The flatter the yield curve, the more cause for concern given the borrower's doubt about the near future.

If there is a lack of demand for short-term bonds, pushing short-term yields higher, perhaps there is doubt about short-term economic growth. Similarly, if investor demand for long-term bonds keeps long-term yields low, this may mean investors don't believe there are inflationary pressures because the economy isn't viewed as trending stronger.

A Side Note: In general, interest rates and bond prices fluctuate like two sides of a seesaw--when one side move the other react in opposite. This is the law of economics at work. In other words, when interest rates move higher bond prices move lower -- or vice versa. So if there is a lack of demand for short-term bonds, short-term bond prices move lower because no one is buying them and causing their prices to drop while at the same time pushing their short-term yields higher. The law of economics at work.

Short-term yields are also artificially pushed up by the Federal Reserve since the Fed Funds rate is the overnight lending rate -- the shortest of the short. An investor needs to make a calculated guess as to how often and how aggressively the Federal Reserve will raise its Fed Funds rate and how the bond market will react to such moves.

The bond investor wins if inflation comes in below expectations. Inflation comes in below expectations when economic growth comes in below expectations. The stock investor wins if economic growth comes in above expectations, generating stronger corporate earnings growth, while interest rates remain at a level high enough to contain faster-than-expected inflation while not choking off investment growth.

Why A Flattening Yield Curve Is A Warning Sign

Depending on who you talk to, flattening yield curve means different thing to different people. Some say a flattening of yield curve is a signal of an impending doom of the economy, but some skeptics say the curve has been distorted by central banks' bond-buying programs, which have artificially made the curve flatter than it might have been. So the curve is a bad signal to predict the health of the economy, they say.

Some strongly believe that an inverted yield curve is a clear signal that some sort of recession is forthcoming. They point out that every recession since the 1950s has been preceded by a yield curve inversion. While the lag between inversion and recession has varied between six months and two years, the one has always followed the other, with only one exception in the mid-1960s, they say.

"Historically, an inverted curve has been the single best indicator of market expectations," said Thanos Bardas, a managing director at Neuberger Berman. "The pattern moves from higher inflation to excessive tightening to an inversion and then a recession."

Normally, the Fed intends for that pattern to occur in order to slow an overheating economy. With inflation finally trending near the Fed's stated target of 2 percent; however, it can hardly be characterized as high. Bardas, too, believes that the Fed should be responsive to market forces and not risk an inversion of the yield curve. "If the curve continues to flatten, the Fed may need to pause [its rate hikes]," he said.

Why is the yield curve flattening? The simple answer is the rapid rise of the 2-year Treasury yield. It has risen much faster than changes in the Fed funds rate because the market now believes that the Fed's policy path is more certain given the strong economy.

But some believe otherwise, "... this time it's different," a UBS economist told clients (in a tongue-in-cheek way). He called the curve signal a "myth."

So who's to believe?

A sensible answer to that question is probably: both.

In other words, be wary and proactive and always taking steps to protect your investment.

Investments can be made profitable when the market goes up, down, or sideway, if you are willing to just learn a few simple options strategies to take advantage of the market conditions. Use options is the most profitable way to take advantage of the market conditions when it is falling.

You don't even need to know ahead of time if the market is in a recession, you only need to watch the market periodically and when the market sentiment is trending lower you can put your strategies to work during the down turn cycle, because bear market stays for a while and it doesn't just go down in or two days--it usually moving gradually lower and lower. This way, you can catch its downward spiral and make money in the process. So yes, bear markets can be a profitable investment if you take time to learn a few strategies using options.

Take a look at the yield curve below for today August 2018 versus the yield curve in 2017 and 2016. It's clear the yield curve has flattened as short-term rates have risen faster than long-term rates.



As you can see from the diagram above, the top line in dark purple color is the U.S. Treasury 10-year yield and the bottom line in light blue color is the U.S. Treasury 2-year yield.

Short-term (U.S. Treasury 2-year) rates are rapidly equaling long-term (U.S. Treasury 10-year) rates. See the below graph:



If the Fed raises the Fed Fund rate by another 0.5% in the next 12 months the yield curve will be completely flat if not inverted by 2019 if long-term rates stay the same.

With a flat yield curve, you are disinclined to lend money over a long duration because the return is too low relative to the short-end. As a result, you tighten up lending standards and lend to only the most creditworthy people. You'd rather lend money for as short a time as possible because the interest rate you can receive is similar to the long-end. A shorter lending time horizon is also less risky than a longer time horizon.

Unfortunately, borrowers think exactly the opposite. Borrowers are less inclined to borrow capital short-term if the interest rate is very similar to long-term interest rates. They'd rather borrow at the same rate for a longer time period, but are often shut out due to more stringent lending standards.

If the yield curve inverts, i.e. when short-term interest rates are higher than long-term interest rates, the rational borrower slows or stops his borrowing. Only the most desperate (least creditworthy) borrower takes out a short-term loan at a higher interest rate (e.g. credit card and loan shark borrowers). This ultimately ends up hurting both the lender and the economy long-term due to higher default rates.

A cascade of defaults by overstretched mortgage debtors is exactly what took the housing market down between 2007-2010. There will eventually be an interest rate inflection point where the borrower not only stops borrowing, but starts saving more. With borrowers saving more, investment, by definition slows down. Multiply this action across millions of people throughout the country and the economy will turn south.

This Time Is NOT Different

In economics and finance, everything is rational long term. Investors take action to enrich themselves, while doing their best to avoid actions that will make them poor.

The tricky part is not forecasting if a recession will happen once the yield curve inverts. The tricky part is forecasting when the recession will happen. If the Fed raises its Fed Funds rate by more than 50 basis points over the next 12 months, the yield curve will most likely be inverted as I'm of the belief long bond yields stay flat.

Therefore, the logical conclusion based on history is that a possible recession will arrive by 2020. I want to caution and emphasize the word "possible" but also be mindful that it is not likely to happen in 2020. Maybe beyond 2020 looks like more realistic given the Fed's anormous power to steer the economy. Of course, long bond yields can rise to prevent the inversion, but higher rates slow down economic growth. Therefore, either way, strong head winds are coming, whether it happens in 2020 is not known.

Yes, banks have taken measures to shore up their balance sheets and tighten lending standards since the last recession. But we cannot underestimate greed or the stubbornness of the Fed to over-tighten to prevent inflation from getting out of control. Everyone should be paying attention to a flattening yield curve and take precautionary measures to protect their wealth.


Do you ever wanted to know how they calculate indexes?

Synopsis: We (Economists) love indexes and know how to create and calculate indexes. It's a requisite!

An index is a number that measures the change in value over time. In other words, an index is a measure of value over time; the change in value over time. For example, an index number is used to measure changes in national income, employment, production, prices, wages, etc., over a period of time.

Some well-known examples of indexes include the Consumer Price Index (CPI), Standard & Poor's 500 stock index, better known as the S&P 500, and of course, the Dow Jones Industrial Index, also better known as the Dow or Dow Jones.

Working with a group of large numbers is sometimes inefficient and confusing, and an index allows you to use a simplified value to easily compare and track against other data points over time.

For example, the U.S. as a whole provides about 140 million jobs. Using an index to simplify the numbers, you can easily compare its percentage job growth over time to that of other states, such as of Texas, even though Texas has only about 20 million jobs.

Converting the data to index values makes it easier to see the percentage change each year when comparing the two sets of data side by side, even though the magnitude of jobs for the whole U.S. dwarfs the number of jobs in Texas.

When using an index to track changes over time, you may find that the data changes and becomes less comparable to the original, or base data. For example, when tracking unit sales of a product over time, the price may experience a permanent increase. Although unit sales of the product haven't actually grown, the index shows growth because of the products new, higher price.

In terms of an index measuring changes over time using a market basket of goods and services, such as the CPI, some goods or products may increase in price, change in quality or other features that make them no longer comparable against the original base value of the index or its earlier data points. Compensating for this issue, although not a perfect solution, would require updating the base basket of goods and earlier data points periodically to reflect and compensate for these types of changes.

The Base Calculation

To start an index, you have to start with a base value so that you can compare the changes in actual value over time against this base value.

An index starts with a base value, typically set at 100, regardless of whether the index measures data units in dollars, euros, or headcount, for example. Each subsequent value in the index is then normalized to this base value. When looking at the percent change between different calculated index values, you will find that it's exactly the same as the un-normalized or non-indexed data percent change.

Using an index to measure changes in data allows you to calculate the percentage change between the points in the index without the need to know the actual data numbers. The index points become normalized when dividing each number by its base value, meaning that the values on different scales become converted into a common scale for ease of comparison.

Calculate Index Values

The first step in constructing an index involves setting the base value. For a time series of annual company sales, for example, say the first year, sales were $150,000. This base-year amount is set to equate to the starting index value of 100. Each added value becomes normalized against the base value. In other words, each added value is the change of value from the base value. If you multiply this change in value by 100, you'll get the percentage value that is changed or different from the base value. See the following examples to get a better idea.

To calculate the value of the next data point in this indexed time series, let's say, the second year of annual sales equates to $225,000. You would divide the new data point ($225,000) by the original one ($150,000), multiplying the result by 100 as follows to get a year 2 index value of 150.

(Year 2 sales of $225,000 / Base year sales of $150,000) * 100 = 150

What does the number 150 represent?

Well, you could look at it this way and say the annual sales has increased by 50% (base value is 100 plus half that value in year 2 to equal 150). The number 150 is the index number for the second year representing the annual sales. Had the annual sales gone down, say to $75,000, the index number would have reflected this decrease in value of 50% to an index value of 50.

Remember that the base value of the index is 100 and the second year index is 50 -- dropping half of its base value. Indexes go both ways, up or down following the real world activity. Likewise, the Dow Jones has gone up from the base value of 100 at its inception more than 100 years ago to right around 25,000 as of this writing (October 2018).

Each new year of data is subsequently normalized against the base year of $150,000 in the same fashion. If years 3, 4 and 5 had sales of $325,000, $385,000 and $415,000, the corresponding calculated index values would be 217, 257 and 277, respectively. For example:

(Year 3 sales of $325,000 / Base year sales of $150,000) * 100 = 217

(Year 4 sales of $385,000 / Base year sales of $150,000) * 100 = 257

(Year 5 sales of $415,000 / Base year sales of $150,000) * 100 = 277

Let's see another example to help you understand better. Suppose that in your own household you buy food items on a regular basis for your household consumption. To track how those prices rise or fall, you can create and calculate an index called it a Household Price Index (or HPI) similar to the well-known CPI index. Since this index is for your own household consumption purposes, it only contain a few food items.

Let's say year one these items cost:

  • pork costs $6.89 per pound. This base-year amount is set to equate to the starting index value of 100.

  • fish cost $14.99 per pound. This base-year amount is set to equate to the starting index value of 100.

  • bread costs $4.89 per loaf. This base-year amount is set to equate to the starting index value of 100.

  • milk costs $5.49 per cart. This base-year amount is set to equate to the starting index value of 100.

  • lettuce costs $2.89 per head. This base-year amount is set to equate to the starting index value of 100.

Here, we are tracking five items so we have to calculate each item's index first and then average them to get the final index number. To calculate the subsequent years you can create an index formula chart for easy calculation and plug the prices you get from the store into this chart. For example, if year 2 comes around and you go to the store and get the exact new prices and plug them in this chart and calculate them accordingly. For example:

  • For pork: (new price / base price of $6.89) * 100 = ?

    If new price is $6.99, then the index for pork is 101.45.

  • For fish: (new price / base of $14.99) * 100 = ?

    If new price is $15.59, then the index for fish is 104.

  • For bread: (new price / base of $4.89) * 100 = ?

    If new price is $4.99, then the index for bread is 102.50.

  • For milk: (new price / base of $5.49) * 100 = ?

    If new price is $4.99, then the index for milk is 90.89. Notice that the price of milk has gone down 9.11% from the previous year. This will effect the overall index number.

  • For lettuce: (new price / base of $2.89) * 100 = ?

    If new price is $2.99, then the index for lettuce is 103.46.

Now to get the final index number we have to average the five index numbers by first adding: 101.45 + 104 + 102.50 + 90.89 + 103.46 = 502.30 and then dividing the result by 5. For example:

502.30 / 5 = 100.46

What does the number 100.46 mean?

Well, this number is the index number for the HPI in the second year of the existence of the HPI. It tells us that the food prices as a group of five items have increased only 0.46% from the year before. Hardly any changes. However, if you look at the individual item the general food prices has gone up about 3% and only one particular item (milk) that has gone down significantly about 9.11%.

That one item pulls down the final index number significantly and that's why the CPI uses a lot of food items (several hundreds of them) in their calculation so that if any one item rises or falls dramatically it won't effect the overall (final) index number that much.

Any subsequent/given year down the road, you can just get the actual new prices from the store and plug them in the chart and calculate them accordingly as it was done above.

Conclusion: The Dow Jones Industrial Index (containing 30 stocks) and the Consumer Price Index (containing a basket of food items) are calculated in similar fashion. Now you know how indexes work and know how to create and calculate them. You can use this example to create and calculate your own indexes to suit your objective. It's a powerful method of measuring things. Have a go at it!


Do you ever wonder how analysts get all the information about a particular publicly traded company?

The first place to get the information about a particular company is not at the company itself, but at the Security Exchange Commission webiste. Publicly traded companies report all information to the SEC and the SEC makes all information available to the public.

At the SEC website, you can find a company's financial statements and information about its operations. Companies making a new offering of securities, e.g., IPO, secondary offerings, must disclose information about the company's financial condition and its operations in a registration statement.

Each year companies must file an annual report about its financial condition and its operation. The annual report filed on Form 10-K is the primary document you can use to research a company's financial condition and its operations. The Form 10-K includes audited financial statements, a discussion of products and services, a review of operations, management discussion and analysis, and a discussion of the company's major markets.

The condensed financial statements included in the filings provide the company's assets, liabilities and earnings per share. Since the passage of the Sarbanes-Oxley Act of 2002, an issuer must include certifications from the issuer's CFO and CEO concerning the accuracy of the Form 10-K (and Form 10-Q as well). These certifications (the Sections 302 and 906 certifications) generally are attached to the filings as Exhibits 31 and 32.

In addition to the annual report, companies must also file quarterly reports using Form 10-Q. The quarterly reports filed on Form 10-Q will include unaudited financial statements as well as additional information about the company's current financial position and operations.

The SEC has a wealth of databases information about companies and the information is searchable using keywords or phrases. The SEC has a specialized database engine called EDGAR (an acronym for Electronic Data Gathering, Analysis and Retrieval).

EDGAR is the electronic filing system created by the Securities and Exchange Commission for easy and flexible to use while helping increase the efficiency and accessibility of corporate filings. The system is used by all publicly traded companies when submitting required documents to the SEC. Corporate documents are time sensitive, and the creation of EDGAR has greatly decreased the time it takes for corporate documents to become publicly available.

Here are typical questions that have been asked:

Where can I find market information about a company, including market risk?

The primary sources for market information are the registration statements, prospectuses and annual reports filed on Form 10-K. In addition to providing a description of the class of securities, these documents will disclose:

The primary market(s) where the security is traded. If there is no established public trading market, the issuer will make a statement to that effect.

Where can I find information about a company's business (including segments)?

Registration statements, prospectuses, and the periodic reports filed on Form 10-K and Form 10-Q will provide a general description of a registrant's business, its subsidiaries, and any predecessors over a five year period (or less if the company has not been in operation for five years). The filings will disclose:

  • The year the company was organized.

  • The company's form of organization.

  • Principal products produced, the principal markets for the products, and the methods of distribution.

  • Number of employees and anticipated material changes in the number of employees in various departments.

  • Competitive Conditions.

  • Research and Development.

Where can I find information about a company's legal proceedings?

Information concerning material pending legal proceedings other than "ordinary routine litigation incidental to the company's business" must be disclosed in the company's registration statements and periodic reports filed on Form 10-K and Form 10-Q. In general, claims for damages do not have to be disclosed if the amount, exclusive of interest and costs, does not exceed 10 percent of the registrant's current assts. However, the issuer must disclose information concerning any material bankruptcy, receivership, or similar proceeding (including those involving a subsidiary).

Under current rules, a company also must disclose the filing of a bankruptcy petition on Form 8-K (Item 1.03) four days after the event.

Where can I find a company's articles of incorporation and by-laws?

Although they may be incorporated by reference, you can find a company's articles of incorporation and by-laws in Exhibit 3 to registration statements filed on Forms S-1, S-4, S-11, F-1, F-4, 10, and periodic reports filed on Form 10-K and Form 10-Q.

Where can I find a list of a company's officers and directors?

Registration statements and periodic reports filed on Form 10-K and Form 10-Q include the names and background information about the registrant's executive officers and directors. An issuer may incorporate this information by reference to either the proxy materials or to the annual reports to shareholders. A company must disclose the resignation of a board member in Item 5.02 of Form 8-K (prior to August 23, 2004, these changes were disclosed in Item 6 of Form 8-K).

Where can I find a list of a company's subsidiaries?

A list of subsidiaries must be disclosed to the SEC as Exhibit 21 to registration statements filed on Forms S-1, S-4, S-11, F-1, F-4, 10, and the annual report filed on Form 10-K.

What types of "material contracts" must an issuer file as Exhibit 10 to a registration statement or periodic report?

Items 601(b)(10) of Regulation S-K and Regulation S-B describe what constitutes a material contract. Examples of material contracts include:

  • Asset Purchase Agreements.

  • Bridge Loan Agreements.

  • Cash Bonus Plans.

  • Director Fee Agreements.

  • Director Indemnification Plans.

  • Employment Agreements.

  • Executive Compensation Plans and Incentive Plans.

  • Financial Services Agreements.

  • Joint Venture Agreements.

  • Lease Agreements.

  • Letters of Intent.

  • License Agreements.

  • Pension Plans.

  • Profit Sharing Plans.

  • Purchase Agreements.

  • Stock Option Agreements.

  • Stock Purchase Agreements.

  • Termination Agreements.

Executive Compensation

Where can I find information about the compensation of a company's officers?

The easiest place to look up information on executive pay is the annual proxy statement. Definitive proxy materials generally are identified in SEC's database provider called EDGAR as form types DEF 14A. For filings in compliance with the changes to the disclosure provisions adopted in 2006, investors should look at the Summary Compensation Table and the Compensation Discussion and Analysis.

Insider Transactions

When must corporate insiders disclose their transactions in the issuer's securities?

Forms 3, 4 and 5, describes the disclosure requirements for corporate insiders. In general, changes in ownership are reported on Form 4 and must be reported to the SEC within two business days (this reporting time frame became effective on August 29, 2002).

Can I search for insider transactions by the individual's name?

Yes. You can search the EDGAR database by typing in the individual's last name and first name in the box marked company in the Companies and other Filers search page. You also can search by the individual's CIK number.

Must all corporate officers disclose their transactions?

No. Rule 16a-1(f) defines who is an "officer" for purposes of filing Forms 3, 4, and 5. These individuals include, but are not limited to, the issuer's president, principal financial officer, principal accounting officer, and the vice-presidents of the issuer's principal business units or divisions.

Can I search EDGAR only for insider forms?

Yes. You can limit a search to the insider transaction forms by clicking the radio button marked "only."

Can I find a list of all insider transactions for a specific time period?

Yes. In addition to doing a header search by form type and date, you can find insider transaction reports for previous five business days by using the current events analysis. However, you will not be able to limit your search to only Forms 3, 4 and 5.

Why can't I find Forms 3, 4, and 5 filed prior to June 2003?

Prior to June 30, 2003, the SEC did not require that Forms 3, 4 and 5 be filed electronically through EDGAR, although filers had the discretion to do so. You can submit a request for a hard-copy of these manually-filed forms.

Business Combinations

Can I obtain a list of companies involved in mergers and acquisitions through EDGAR?

No. EDGAR does not organize filings in this fashion. However, you can do header searches for specific periods of time to find filings used in connection with mergers and acquisitions such as the Form S-3, Form S-4 and proxy materials.

Can I find the terms of a specific merger or acquisition in EDGAR?

Yes. You can look at Form 8-K. Item 1.01 of this form requires disclosure of information concerning the entering of material definitive agreements; Item 1.02 requires disclosure of the termination of such agreements. Item 2.01 requires the disclosure of information relating to the completion of the acquisition or disposition of corporate assets. You also can look for exhibits to periodic reports filed on Form 10-K and Form 10-Q.

If the merger or acquisition required a vote by shareholders, the agreement also is available in the proxy material file with the SEC on Schedule 14A.

Initial Public Offerings

Can I find a list of upcoming IPOs on EDGAR?

No. Although you can search for registration statements filed during specific time periods, the data available through EDGAR is not organized by upcoming IPOs. If a registration statement is effective, you may want to check the exchange or market where the security will be listed or quoted to see when the IPO is scheduled.

How do I find out the date of an upcoming IPO?

An issuer must file both a registration statements and a prospectus with the SEC. However, these documents will not include the intended date of the IPO. Rather, the company determines the date of the IPO once it meets the listing requirements of the exchange or market where the securities will be listed or quoted.

Where can I find historical information about IPOs?

EDGAR does not include a list of historical IPOs. However, if you are looking for the IPO date for an offering made by a specific company, you can check the periodic reports filed near the time of a registration statement to see if they reference the date of the IPO.

If a company files a registration statement with the SEC, when will the IPO occur?

The filing of a registration statement does not mean that the IPO will occur. First the registration statement may be amended one or more times before it is effective. Even after the registration statement is effective, the company may not pursue the IPO.

What is a "shelf" registration?

Issuers may use a Form S-3 registration statement for securities to be offered on a delayed or continuous basis. Issuers use "shelf" registrations when they want securities to be offered as quickly as possible once funds are needed or market conditions are favorable.

Since December 2005, "automatic shelf registrations" have been available for certain issuers (i.e. "well-known seasoned issuers"). Automatic shelf registration permits automatic effectiveness, pay-as-you-go registration fees, and the ability to exclude additional information from base prospectuses.

Bankruptcy

Where can I find the date a company filed a bankruptcy petition?

You can find this information in Form 8-K. Prior to August 23, 2004, the disclosure was in Item 3 of the Form. The information is now disclosed in Item 1.03 of the Form. The information also may be reported in Form 10-Q and Form 10-K.

Where can I find the identity of the Court where a company has filed its bankruptcy petition?

An SEC registrant must disclose in Form 8-K the identity of the Court where it filed its bankruptcy petition.

Where can I find information about a company's reorganization or liquidation plan after filing for bankruptcy?

A company must disclose the material features of a reorganization or liquidation plan in the Form 8-K. A copy of a plan as confirmed by the Court must be disclosed as Item 9.01 of Form 8-K.

Are SEC registrants relieved of their obligation to file periodic reports with the SEC?

No. Companies in bankruptcy are not relieved of their reporting obligations. Neither the United States Bankruptcy Code nor the federal securities laws provide an exemption from Exchange Act periodic reporting for issuers that have filed for bankruptcy.

However, the SEC generally will accept the monthly reports an issuer must file with the Bankruptcy Court under Rule 2015 in lieu of Form 10-K and Form 10-Q filings. The issuer must file each monthly report with the Commission on a Form 8-K within 15 calendar days after the monthly report is due to the Bankruptcy Court.

Here is how to get started programming for beginners

If you ever wanted to learn how to program computer programs, particularly learning how to build a website of your own, this tutorial helps you get started and points you in the right direction to achieving your programming goal. This tutorial is not meant to teach you everything about how to program, but rather, a 'get started' guide that guides you in the right direction to help you get started.

For a complete and specific area of programming, such as a particular language you are interested in learning, please check out tutorials on the Web by Googling it. There are lots of free tutorials on the Internet, particularly YouTube.com and the HTML as noted in the following.

A good place to get started is the W3Schools

And here is another good place to get started:

Learn How to Code Online

And here is a forum for the above site where you can ask the experts on programming topics:

Learn How to Code Online: Codecall Programming Forums!

As listed in the W3Schools mentioned above, you need to start with HTML and CSS first, and then proceed to server-side languages such as PHP and then to the client-side languages such as Javascript, and then you should learn databases as well, such as PDO and MySQL, and then to specialized languages such as jQuery and Ajax, in that order. So the order you should follow is: HTML, CSS, PHP, Javascript, PDO, MySQL, jQuery, Ajax.

If you have time, you should learn DOM as well. For an introductory course on DOM, see chapter 3 to 7 of my Ajax book called Introduction to Ajax.

If you mastered all the languages mentioned above, you should be able to build any sophisticated Web applications easily. After that, if you want to learn other languages as well, then you should learn those languages listed in the W3Schools mentioned above in no particular preferential order guideline.

W3Schools above listed category under Javascript, which includes Node.JS and other excellent server-side languages as well, but you really only need to learn PHP is enough for a while. PHP is the most popular server-side language out there, but Node.JS is getting more popular as it is very good in streaming applications, such as movie shows and other live streaming applications.

However, you can accomplish the same thing using PHP, but it is easier to program streaming applications using Node.JS than PHP as Node.JS is specifically built for streaming applications.

If you want to learn how to program sophisticated desktop applications, start with Java, and then C++, and then either Python or C# (pronounce 'see sharp') or even Delphi if you dear to venture into the deep end of the programming language world. But the first three or four listed above is sufficient and you can accomplish any sophisticated desktop applications just fine.

If you just want to learn only one desktop language, Java is a very good choice to learn.

If you dear to venture into the deep end of the programming language world for desktop, here is a link to an excellent language called Delphi

If W3Schools doesn't have the topics I mentioned here, just Google around and you'll get plenty of results for you to get started. Have fun learning!

Here are the steps on how to get started programming for beginners:

  1. First, you need an editor to write your programs with. There are lots of free editors on the Web such as NetBeans IDE, a free, open-source Integrated Development Environment for software developers. You get all the tools you need to create professional desktop, enterprise, web, and mobile applications with the Java language, C/C++, and even dynamic languages such as PHP, JavaScript, Node.JS, Groovy, and Ruby.

    NetBeans IDE is easy to install and use straight out of the box and runs on many platforms including Windows, Linux, Mac OS X and Solaris.

    Other text editors that are very popular among beginners are Notepad++, Sublime Text, Atom, Ultra Edit, TextMate, BBedit, MAX's HTML Beauty++, etc. Please Google them to learn more about them. Or you can just Google the term 'free text editors' and you'll get a bunch of results.

    Personally, I have been using two text editors simultaneously: one is NetBeans IDE because I need to compile and run programs written in Java for desktop applications and another is MAX's HTML Beauty++ for doing non-desktop applications for the Web, such as Javascript, Node.JS, HTML, CSS, etc. MAX's HTML Beauty++ is perfectly suitable for these Web languages.

    What I like about MAX's HTML Beauty++ old version is that it color-codes all PHP code in yellow and leaving all other programming languages code as a default color, which is a non-color!

    Using MAX's HTML Beauty++ old version, you can preview your webpages instantly while you're still building it by switching back and forth between a "preview" and an "edit" mode. This is a great feature for beginners trying to learn how to program web applications.

    If you are not into building sophisticated desktop applications, here is MAX's HTML Beauty++ download that will do the job just fine for building Web applications.

    The download above is an older version, which happens to be my favorite version that I am still using it to this day, and I prefer this older version over the newer version, which is a 2004 version. If you prefer the newer 2004 version, here it is: http://www.htmlbeauty.com/bsetup.exe download

    As a matter of fact, any text editor, including Microsoft NotePad that comes with your Windows operating system, will do just fine for building Web applications.

    Also all these downloaded text editors come inside an archive compression zip file. You need to extract them once you've downloaded them using any archive unzip application. There are lots of free archive zip applications available on the Internet. See the following.

    Once you've downloaded your favorite text editor, extract it using free zip extracting applications like WinZip Express Zip WinRAR or WinRAR here! PeaZip

    Once you've downloaded your favorite archive zip application, you need to install it as you normally would with any other applications by following the installation instruction. It shouldn't be that hard to install the archive zip application. You can install it in any directory of your choosing and it doesn't need to be in a particular directory at all.

    Just make sure that you say "yes" when it prompts (you) if you want the installation program to create an icon in the desktop for that particular archive zip application. If you said "yes," it will create an icon for that archive zip application and it will put that icon on your desktop pane. Self-explanatory!

    Actually, you don't even need to have the icon shown on your desktop pane unless you need to open it to create an archive zip application to put your files in to send your files to the server. In that case, you definitely need to have an icon shown on your desktop pane.

    So basically, after you'd installed your favorite archive zip on your laptop/desktop you can use it to extract your downloaded text editor that came inside the zip archive by clicking on your "raw zipped" downloaded favorite text editor.

    Remember that all downloaded applications come inside an archive compression zip application -- it is totally zipped or compressed. So you need to extract/uncompress the downloaded text editor, which came inside the archive compression zip application.

    Just clicking on the "raw zipped" downloaded text editor in raw format and it will open up (automatically) the archive zip application that you had installed on your computer. You see, this is why you don't need to create an icon on your computer pane because you don't need to click it to open it. It opens the archive zip application automatically every time you click on the "raw zipped" downloaded application.

    Once it opens up the archive zip application it should show that your text editor is inside the archive zip application. In that archive zip screen, it shows a lot of options you can do, such as "create archive" for creating archive zip application packages, and "extract" option, which is to extract the (current) downloaded application. Follow the on-screen instruction and you'll be fine! It is very easy to use archive zip applications.

    If for some reasons you need to send files to the server, you can open the archive zip application by just clicking on the icon shown on your computer pane and it will open the archive zip application for you to use. This is why you need to allow the installation program to create an icon on your computer pane so that you can open it and use it easily.

    Let's say you have some photos, or any other content for that matter, and you want to send them to a remote server, you can put those photos/content/files in an archive zip application and send them to your remote server or any server you have accessed to. And then create a link to that archive zip file name and your users will be able to download those content from your website.

    For example, say you have a bunch of photos and you want to create an archive zip application by opening the archive zip application and then clicking on "create archive" or for some archive applications just say "create", and it will open a screen to allow you to create the archive zip application. From there, just follow the on-screen instructions and you'll be fine.

    Among the instructions is that it asks for a file name for the archive zip application you're creating; for example, you can name it as "myphoto" without any extension and it will create an empty archive zip application without any content in it.

    From there, you can put your photos/content inside that newly created archive zip application by copy and paste them or if the photos/content/files are on the computer pane, you can drag and drop them easily. It is very easy to create and move content into the archive zip applications.

    Now you have your photos/content/files inside your newly created archive zip application with a file name for that archive zip application and ready to go. Next, you can upload the entire archive zip application to your server so that your users can download them.

    To allow your users to download them, you need to create a link to that particular archive zip application that you just uploaded to your server. For example, say you upload your archive zip application to your website, which has a directory called "download," you can create a link somewhere on your website page like this: <a href="http://www.mywebsite.com/download/myphoto.zip">download my photos!</a>. That is it!

    Pay special attention to the extension, which in the above case, it is a ".zip" extension. So you need to specify the exact extension in order for it to work. Different archive compression applications have different extensions and they are named accordingly in a variety of extensions, i.e., .zip, .ar, .rar, .pea, etc. Check your particular archive compression applications for the extension they use.

    Well, the first step is a little too lengthy than I would have liked but I just wanted to be very clear and precise to help you along!

  2. Next, you'll need a local webhost to build and test your applications offline -- that is, you're using a fake web server to build and test your web applications offline on your computer without having to rent a live "real" web server. Once you've built and tested your web applications offline, you can decide to get a real web server to host your web applications online so that your website can be viewed by people all over the world.

    As a matter of fact, most experienced programmers, including myself, use "fake" server to build and test applications on a daily basis. So I strongly recommend beginning programmers to do the same and use localhost to build and test your web applications. Once you finished building and testing your applications and then you can find a real web server to host your websites. Google around using phrases like this: "free webhosting services" to find a real web hosting service provider to host your websites. There are lots of them out there.

    Check out my other tutorial at the bottom of this page titled: 'Migrating your website to a real live server' for a free web hosting service provider that I found on the Internet when I Googled around using phrases like this: "free web hosting services".

    That free web hosting service provider that I found is one of the best free web hostings out there. I used that free web hosting to host one of my websites as well. You, too, can signup for a free web hosting account with them and use it to host your website just like I do.

    Please DO NOT use free web hosting to build and test your web applications because it slows down other people using the same host. All free web hostings are shared hosting: meaning all users of the shared hosting are routed through the same bandwidth and if lots of people use their live hosting to build and test their web applications, it slows down the shared hosting traffic.

    So please use your localhost to build and test your web applications.

  3. To get a "fake" web server, usually called localhost, you can search the web using a term like "localhost webserver", or you can Google a specific term like "WAMP server", "XAMPP server", "MAMP server", "VAGRANT server", or DOCKER.i.

    Once you've identified which one you want, go ahead and download and then install it on your local machine, preferably on your laptop/desktop. You can choose to install it in any location on your desktop/laptop and it doesn't matter; however, for ease of use, choose the default setting shown on the installation prompts.

    Once you've installed your localhost web server, you're ready to build and test your web applications just like if you had rented a real live web server from a hosting vendor. The only difference is that your "fake" web server is locally run and is not visible on the web like a real web server does. Most of the instructions on the web are self-explanatory and are very easy to follow even for beginners who never know how to program a single program. You can check out Youtube.com on tutorials on these topics as well.


Here is a very brief tutorial on how to download and install a localhost called WAMP server.

First off, for all beginners, it is essential to understand the purpose of using WAMP and the significance of WAMP. Basically, WAMP stands for Windows (operating system), Apache (web server), MySQL (database), and PHP programming language: all bundled into a single platform called WAMP.

Once you've installed a WAMP local host web server, all the required applications, such as the Apache (web server), MySQL (database), PHP programming language, and as well as the PHPmyAdmin (a MySQL application), are all bundled and installed completely into your local laptop/desktop to work with each other seamlessly.

In WAMP, you can work with databases using MySQL to store and retrieve data, as well as using PHP programming language to program your web applications. WAMP is not restricted to just PHP, however -- you can use other languages as well.

WAMP is a popular alternative of XAMPP for Windows. However, you can use XAMPP as well and it doesn't take much time to install XAMPP either. But developers may prefer to use WAMP since it is specifically crafted for Windows only -- unlike, XAMPP, which can be used for Linux and Mac OS as well.

However, both platforms are equally stable and provide the same functionality.

So you can choose any platform amongst the two to fulfill your objective. But all those who are searching for guidance on how to install WAMP on Windows system should follow the below-given steps. So let's get going!!

How to Install WAMP on Windows

  1. Download the WAMP Server: Wampserver 64 bit x64

    You want to choose a 64 bit version. The 32 bit is for older computers or laptops, which is outdated in today's programming world. If you're using computers that is still using a 32 bit, by all mean choose 32 bit version. To check what version your computer is running on, go to the status bar at the lower left corner of your computer screen and type in the search box: control panel and press enter.

    The "Control Panel" screen should pop up. In that screen, look for a section called "System and Security" or "System and Maintenance" or anything that has a word "System" on it. For Windows 7, 8, 10, it should says "System and Security." Click on that topic and a "System and Security" screen should pop up.

    Next, look for the topic "System" and click on that topic and a "System" screen should pop up. In that screen under the "System" section it lists the "System type" which should say a "64-bit Operating System or 32-bit Operating System, depending on your computer. If it says "64-bit Operating System, your computer is running on a 64-bit operating system. "32-bit Operating System", otherwise.

  2. Initiate WAMP Server Installation Process. I'm being lazy and for the rest of the installation instructions, I will refer to an excellent instruction on the web: here it is: click here!

  3. In that instruction, be careful in step 2. WAMP server looks for a version of Microsoft Visual C++ re-distributable package already installed on your laptop/desktop. Most of the laptops/desktops come with a Microsoft VC++ re-distributable package already pre-installed, so you don't have to do anything. However, for some odd reasons, some laptops/desktops came without that Microsoft Visual C++ re-distributable package pre-installed.

    In that case, you might have to search the web for "Microsoft Visual C++ re-distributable package" and download it and install it using default settings contains in its installation application. When you install Microsoft Visual C++, it is very easy and self-explanatory, the same way you install a WAMP server -- they both are self-explanatory, allowing you to just use default settings.

    FYI: If you look in the "Control Panel" screen mentioned earlier, it should shows Microsoft Visual C++ installed already; and in that case, WAMP server will find it and use it to complete the installation process, and thus, you don't need to do anything on your part, sparring you from having to search the web.

  4. Once you get through the Microsoft Visual C++ re-distributable package installation process and proceeds to the end of the installation process, the last thing the WAMP server installation guide will prompt you to do is, to enter/choose a text editor. You can accept a default text editor in the prompt or choose your favorite text editor to use with your newly installed WAMP server. It looks something like this:

    It's okay one way or another as it is not very significant if you do not choose a particular text editor or not as a default text editor for the WAMP server to use. It won't effect/harm your WAMP server at all.

    However, I strongly recommend you just select a text editor of your choice or just leave it as a default text editor that the WAMP server chooses, which is a Microsoft notepad. In other words, by choosing a particular text editor doesn't restrict you from using other text editors with your WAMP server.

    It also will prompt you to enter/choose a default web browser to use with your newly installed WAMP server. Likewise, by choosing a particular web browser doesn't restrict you from using other web browser with your WAMP server either. So it looks something like this:

  5. Once you've finished the installation process, you can use the "fake" web server to build and test your web applications offline as you normally would with a "live" real web server. To start, click on the arrow or status icon usually on the lower right corner of your laptop/desktop screen to activate the tap that shows the "fake" web server options listing.

    Note: From time to time, if you're using Windows operating system, Windows operating system usually runs updates to update its software drivers and the rest of its system files automatically and periodically. If you're using Windows OS, you may have experienced this update many times already and it's kind of annoying as well, but it's a necessary task for Windows OS, according to Microsoft.

    One of the annoying things that this update causes is that it causes the WAMP server to not function properly once the update is completed.

    If you experienced this and having issues with your WAMP server to not function properly, just un-install your WAMP server completely from your system and then re-install it again and it should work properly.

    Yes, it is very annoying having to un-install and re-install your WAMP server every time a Windows operating system runs its update.

    Make sure that you move all of your "projects" in the "www" directory to a different location (or directory) before un-installing your WAMP server; because if you don't, it will delete all of your projects in the "www" directory.

    Let's continue on:

    It should show an icon that looks something like below with a status icon that usually appears on the lower right corner of your laptop/desktop screen, but with a particular color on it. A green color (as shown below) signifies as the wampserver is ready to use; a grey or pink color, it is not activated; a yellow, it is partially ready and in the process of being ready as it is finishing the loading process.

    If it is inactive, all you have to do to fire up your wampserver is to double click on the default icon on your laptop pane that looks something like below:

    Usually, when you turn off your laptop, WAMP server is also turned off and no longer active and the green status icon you see above is not shown. When it is turned off, the status icon that usually appears on the lower right corner of your laptop/desktop screen doesn't show the WAMP server icon because it is not activated.

    To activate it or turn on your WAMP server, double click on the default icon on your laptop pane to get it activated.

  6. Once your "fake" server is up and running, you can do pretty much just about anything you do with a "live" server. You can click on the arrow next to the green status icon to reveal other options, such as a PHP icon to see what version of PHP is installed on your "fake" server; as well as clicking on PHPmyAdmin to work with database.

    Note that PHPmyAdmin in your "fake" server doesn't require you to enter a password, although you can if you want -- but why bother to complicate yourself in having to enter a password every time you try to access your PHPmyAdmin? So just enter 'root' for the username and don't enter a password on the password field. Leave it blank as it is!

    Just click "Go" without entering a password and it will open the PHPmyAdmin panel for you.

  7. In the PHPmyAdmin, you can create databases and tables and do pretty much just about anything about database programming.

  8. As stated above, when a localhost is up and running the status icon usually appears on the lower right corner of your laptop/desktop screen. Click on the arrow to reveal the the localhost options. In this option window, you can find a lot of options to choose from, such as PHPmyAdmin, just to name one.

    You can click on the particular option to work with it. For example, among the options there is a "localhost" option. Click on that "localhost" option and it will open up a screen that looks something like the following:

    As you can see, it shows the configuration status of the localhost such as what version of various entities: Apache, PHP, MySQL, etc. Most of them are really not useful for beginners. Experienced programmers can make use some of these configurations.

    The diagram above combines with the one listed below is what it should looks like inside a real server. This localhost web server mimmicks what a real server looks like but on an offline mode.

  9. The localhost also contains a section in the lower half that lists content that is more relevant to beginning users of Wampserver, such as tools and your actual projects that you had created. For example, below it lists three projects that I've created: advanced, framework, noon2noon.com:

    If you click on one of the projects it will execute/load the project. For example, if I click on the project called noon2noon.com it will load and display my website called noon2noon.com.

    However, you can load your website on the browser's url bar as well, the same way you normally would with your regular "live" server. That is the typical usage of localhost: you don't need to load your website through localhost option window, but instead, through a normal loading process in the browser's url bar.

  10. You should try to create a very simple website and click on it in the project section to see what it looks like on your "fake" server. When you create your projects, place them in a directory where you installed your Wampserver. For example, in my case, I installed my Wampserver in a directory that looks like the following:

    As you can see, my root directory is called "Desktop" followed by a directory that I named it as "wamp64" followed by a directory called "www." This directory called "www" is created automatically by the installation, so you really don't have to create it yourself. The only directory that you need to create and specify during the Wampserver installation is the "wamp64" part or whatever name you choose. I chose to name it "wamp64."

    Any projects you build have to be placed inside the "www" directory in order to be visible by your localhost. For example, in my case, I placed my projects in that "www" directory and inside my project noon2noon.com it contains content that looks like the following:

    One particular content worths mentioning is the index.php file. This is the main starting script file that the server/localhost calls first thing when you try to load the website by typing in your url bar like http://www.noon2noon.com. However, that is for your real live web server when you migrate your website to a real web server.

    But for this tutorial, you're using a fake server called localhost, and, therefore, you have to type in the browser bar using localhost instead of www.

    So you can simply replace the domain specification 'www' with 'localhost' and just type the name of the folder following it as, in my case, http://localhost/noon2noon.com or simply just localhost/noon2noon.com and it will load the website automatically.

    For my project advanced, which its inside content looks similar to my other two projects framework and noon2noon.com, I can just do the same like this http://localhost/advanced, and likewise for the other one http://localhost/framework, and both websites will load automatically.

    Notice that you can include an index.php or index.html file as well since it doesn't require you to specify an extension of either a .php or a .html and it will work just fine. For examples: http://localhost/noon2noon.com/index, http://localhost/advanced/index, http://localhost/framework/index, and all websites will load automatically.

    Please note that when you migrate your websites to a real web server, you have to abide by your web hosting's rule, which tells you what kind of an extension of either a .php or an .html that their server is using. If they're using a .php extension, you'll have to rename your index file with that extension. Likewise, if they're using an .html extension, you'll have to rename your index file extension as such.

    For a localhost, it doesn't matter. It will read from either .php extension or .html file extension.

    For starter, in your case, just create an index.php or index.html file and throw it in a folder and place that folder inside the "www" directory and type http://localhost/ follows by your folder name in the url browser bar to see your website comes alive. Try it!

    If your website doesn't come alive and showing a weird screen that looks like the following, it means that for some reason the localhost cannot read your index file:

    As you can see, there is no index file listed in the main folder. I deleted it on purpose!

    Remember that each website has to have only one index file as a main starting application file. So make sure that you have a functional index file and it has to be only one index file. No index.php and index.html at the same location vying as the main starting application file.

  11. Once you are finished building and testing, you can migrate your projects to your live real web hosting server. For example, in my case, I just take the folder containing the particular project, i.e., noon2noon.com folder, and upload the entire folder to my real live server. That's how you get started in developing website applications.

    For starter, you can create a folder and name it and then create an index.php or index.html file as well as other files/folders and put them inside that folder that you just created which contains other files/folders as well and upload the entire folder using FileZilla. See my other tutorial on how to use FileZilla.

  12. That is it! Very simple to have your own "fake" server. And from here, the possiblities are endless! Have fun programming!


Building a Website for Beginners

For beginners, building a website is a daunting task, even for very simple websites that don't have ordinary bells and whistles and are still very challenging to say the least. Fortunately, the folks at the W3Schools.com provide all sort of examples and ready-made web site templates to help beginners get started.

Let's take a look at one template and illustrate how you (beginners) can build your own web site using the ready-made template and customize it to suite your taste.

First go to https://www.w3schools.com/w3css/w3css_downloads.asp and download the css definition (or file) and place it in a folder called css. The default file name is w3.css. You can rename the css file if you like, say css.css or style.css. If you do, don't forget to change the css file name accordingly in your index.php file at the css area at the top of the index.php file to reflect the change in the css file name.

Next, in the same page where you're downloading the css, look on the left side under the category name Examples and try to find a topic name called W3.CSS Templates. Or you can go to https://www.w3schools.com/w3css/w3css_templates.asp

You can scroll down to see the various templates available to use. Pick one and go from there!

If the templates mentioned in the above link is not enough for your tastes, you can find more templates to use right here!

Once you decided which one you want to use, go ahead and click on the "Try it Yourself" button to see the actual code.

Next, copy the actual code, character by character, without missing any character. In other words, no typos in your part or else your web site won't look as intended. If your web site doesn't look like it is intended, try to go back and see if you had any typos in your copied code.

The folks at W3Schools.com used some sort of techniques, such as disabling the "hot link" ability, to disable the copy and paste ability from the web browser. So you can't actually use your web browser to copy and paste the code shown in the templates. You'll have to use advanced editors or tools to copy and paste the code in the templates.

For beginners, advanced tools are out of reach, so just try to copy it manually by hand character by character until you completely copied everything in the template. Yes, it is a pain, but that is what you have to do to learn. Name that template as either index.php or index.html. This is your main index file -- or your main web site file.

Once you have the css file downloaded as well as the template copied and name it as either index.php or index.html, then you need to create a main folder as well as a css folder.

Next, create another folder called image and put all the images/photos that you want to use in your website in that image folder.

You can name them whatever names you like for any folders you create, i.e., MyWebsite, MyFirstProject (for the main folder), css, style (for the css folder), image (for the image folder), etc.

You need to put the index.php or index.html as well as the css folder and the image folder in the main folder. The css file containing the css definitions should be inside the css folder, while the image folder contains all images you need to use. Self-explanatory!.

So your main folder contains everything you need. So you need to put everything in this main folder, including other folders as well such as css, image, etc. The index file should be among the css and image folders as peers at the same level.

That's all you need for this simple website. Three folders: main folder (i.e., MyWebsite or MyFirstProject, or whatever), css folder, and image folder. Plus the index.php/index.html and all three are peers -- meaning they are at the same level in directory. For example:

Of course, you can have more folders and other contents as well as your website gets sophisticated, but for this simple website the three items are all you need for now.

As you can see, I put my main folder called MyWebSite inside the www localhost folder for building and testing web applications. The index.php file contains the content listed below and the actual rendering page content is shown in the following.

Let's see one particular template called "Social Media Template" taken from W3Schools.com website in the W3.CSS Templates category, but I customized it slightly. Here it is:

Here is the actual code along with the commented out code that contained in the original template shown in the W3Schools.com:

File: index.php

<!-- all HTML document start with a !doctype -->

<!-- it is a Document Type declaration to tell the web browser of -->
<!-- what version of the HTML markup language in which a web page -->
<!-- is written. -->

<!-- every time a browser reads a document such as an HTML document it -->
<!-- needs to know what version the HTML markup language is written in -->
<!-- so that it can parse it correctly. -->

<!DOCTYPE html>
<html>
<head>
<title>Template</title>

<!-- a meta (<meta>) tag provides metadata information about -->
<!-- the HTML document. -->

<!-- a metadata information will not be displayed on the page, -->
<!-- but will be machine/browser parsable. -->

<!-- metadata elements are typically used to specify page description, -->
<!-- keywords, author of the document, last modified, and other metadata. -->

<!-- you put metadata in <meta> tags-->

<!-- meta (<meta>) tags are documents for the browsers to read and -->
<!-- used the meta content, for example, you can specify a view port -->
<!-- device dimension such as width. -->

<!-- the word "meta" means self or itself, referring to itself or -->
<!-- a self-referential. -->
<!-- so a self-referential. -->

<!-- meta tags can contain attributes, i.e., name and content. -->
<!-- the two most frequently used in a meta tag are name and content -->

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- the following link is the css link stored in folder named css -->

<link rel="stylesheet" href="./css/mobile.css">

<!-- the following two links were broken down to fit the screen display -->
<!-- these two links are specialized css stored in cloudflare.com -->
<!-- you only need to incude these links if you use awesome fonds and -->
<!-- bootsrap code like form input boxes, textarea, and dialog boxes -->
<!-- you can check out bootstrap tutorials on W3Schools as well! -->

<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/
                                        css/font-awesome.min.css">
<link rel="stylesheet"
      href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/
                                        3.2.0/css/bootstrap.min.css">

<!-- the following three lines link to jquery, bootstrap, and -->
<!-- my own Javascript files -->

<script src="https://code.jquery.com/w3/1.4.5/jquery.w3-1.4.5.min.js">
</script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="javascript/javascript.js"></script>
</head>

<!-- this is the start of the web site body -->
<!-- the 'class' attribute specifies the css that this body uses to -->
<!-- beautify itself -->
<!-- disregard the theme class, but make use of the color class -->
<!-- this is where you set your body background color, light grey, in this -->
<!-- case! -->
<!-- check out the list of pre-made colors at the bottom of this listing -->

<!-- in this body is where you also set your text size using w3-tiny -->
<!-- w3-small, w3-medium, w3-large, w3-xlarge, w3-xxlarge, -->
<!-- w3-xxxlarge, w3-jumbo -->

<!-- as you use W3Schools templates, you can put multiple css classes in an
     element, i.e., <body>, <div>, <span>, <p>, <a>, <button>, <img>, etc. -->

<body class="w3-theme-l5 w3-light-grey">

<!-- some of the following codes were broken down into multiple lines -->
<!-- to fit the screen display -->

<!-- Navbar -->

<!-- this is the div that wraps around the navbar -->

<div class="w3-top">


<!-- in the navbar you can style the look-and-feel using css classes. -->
<!-- for example, you can make the navbar thicker or thiner by specifying -->
<!-- the class as w3-padding-tiny, w3-padding-small, -->
<!-- w3-padding-large, etc. -->

<!-- in the example site illustrated above I style the navbar as w3-blue! -->

  <div class="w3-bar w3-theme-d2 w3-left-align w3-small w3-blue">
     <a class="w3-bar-item w3-button w3-hide-medium w3-hide-large w3-right
                  w3-padding-small w3-hover-white w3-small w3-theme-d2"
                  href="javascript:void(0);" onclick="openNav()">
                  <i class="fa fa-bars"></i></a>

    <!-- notice that the anchor tags contain "#" used in place ---->
    <!-- of the actual url that you need to provide! ---->
    <!-- the "#" is just a placeholder for the real url! ---->
    <!-- so don't forget to replace "#" with the actual url! ---->
    <!-- for example: "http://www.example.com/homefolder/myfile.php" ---->

    <a href="#" class="w3-bar-item w3-button w3-padding-large w3-theme-d4">
                   <i class="fa fa-home w3-margin-right"></i>Logo</a>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large
                   w3-hover-white" title="News"><i class="fa fa-globe"></i></a>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large
        w3-hover-white" title="Account Settings"><i class="fa fa-user"></i></a>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large
               w3-hover-white" title="Messages"><i class="fa fa-envelope"></i>

    <div class="w3-dropdown-hover w3-hide-small">
      <button class="w3-button w3-padding-large" title="Notifications">
           <i class="fa fa-bell"></i>
           <span class="w3-badge w3-right w3-small w3-green">3</span>
      </button>

      <!-- here is again the use of "#" as a placeholder for the real url! ---->

      <div class="w3-dropdown-content w3-card-4 w3-bar-block"
              style="width:300px">
         <a href="#" class="w3-bar-item w3-button">One new friend request</a>
         <a href="#" class="w3-bar-item w3-button">John Doe posted on
              your wall</a>
         <a href="#" class="w3-bar-item w3-button">Jane likes your post</a>
      </div>
    </div>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-right
       w3-padding-medium w3-hover-white" title="My Account">
       <img src="./image/paul_tuon.jpg" class="w3-circle"
       style="height:23px;width:23px" alt="Avatar"> </a>
  </div>

</div> <!-- end div class="w3-top" -->

<!-- the following code block is the code that gets used instead of the -->
<!-- above navbar when a mobile device is used to load -->
<!-- this web site -->

<!-- Navbar on small screens -->

<!-- here is again the use of "#" as a placeholder for the real url! ---->

<div id="navDemo" class="w3-bar-block w3-theme-d2 w3-hide
   w3-hide-large w3-hide-medium w3-large">
   <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 1</a>
   <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 2</a>
   <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 3</a>
   <a href="#" class="w3-bar-item w3-button w3-padding-large">My Profile</a>
</div>

<!-- now the navbar code is done! -->

<!-- at this point there are 0 open <div> tag -->

<!-- Page Container -->

<!-- remember that there are typically four sections in a web site: -->
<!-- the head section, the navbar section, the main body content, -->
<!-- and the footer -->

<!-- so the following is the start of the main content of the web site, -->
<!-- and this section is the biggest section. -->

<!-- this main container has a maximum width of 1400 pixels -->
<!-- and spaces between the navbar and the start of the main -->
<!-- container or content is 80 pixels. -->

<!-- take a look at the gap in the web site above for a visual guide! -->

<!-- for a better practice is to use percentage as in 100% -->
<!-- of the screen width rather than specifying the exact width! -->
<!-- that way it works much better on different screen sizes! -->

<!-- pay special attention to one class: w3-container -->
<!-- 'container' is sort of a basket to hold something, in this case, -->
<!-- it holds a grid of column layout -->

<!-- in a later case, it holds a (small) profile container area! -->

<!-- as you can see, class w3-container can be used inside -->
<!-- another container area as well -->

<!-- in this case, this w3-container class acts as the main content -->
<!-- holder, holding everything in the body of the entire page! -->

<!-- remember that the whole website has four sections: navbar section, -->
<!-- head section, the main body section, and the footer section! -->

<!-- so this div has a w3-container class to hold the entire content -->
<!-- and this entire content is actually the 3-column layout grid! -->

<div class="w3-container w3-content" style="max-width:1400px; margin-top:80px">

  <!-- The Grid -->

  <!-- W3Schools provides grid system for us to use! -->
  <!-- for a complete in depth tutorial see W3Schools on this topic! -->

  <!-- pay special attention to a class called w3-row -->

  <!-- so two classes that are central to W3Schools framework are -->
  <!-- w3-container and w3-row -->

  <!-- you'll make use of these two classes very often! -->

  <!-- basically, the grid must be inside the container: w3-container! -->
  <!-- and the container, w3-container, can contain rows of content! -->

  <!-- this grid starts with a class w3-row -->
  <!-- this is sort of the anchor div to hold the entire grid or one row! -->

  <!-- class w3-row is a grid system. think of w3-row as a table row where -->
  <!-- you can arrange grid data content in it. so if you have data content -->
  <!-- that are normally arranged in rows in a table, you can use this -->
  <!-- w3-row to hold those data content in table rows-like display! -->

  <!-- however, in this website we have only one row of a table row! -->
  <!-- if we have more data content that needs another table row, all we -->
  <!-- have to do is create another div containing this w3-row class and -->
  <!-- put it after the closing of this div shown below! -->
  <!-- see the closing of this div later! -->

  <!-- if you look at the website illustrated above, you'll see the -->
  <!-- whole content body is inside a div that contains the class w3-row. -->

  <!-- this is one row of content containing a three-column layout. -->

  <!-- after the closing of this div w3-row, you can create more rows -->
  <!-- of content by creating more divs that contain the class w3-row. -->

  <!-- for each div that contains w3-row you can format your grid layout -->
  <!-- any way you like, say, a four-column layout or whatever layout -->
  <!-- configuration you desire!  -->

  <!-- here is the row! -->

  <div class="w3-row">

    <!-- here is inside the row! -->

    <!-- now inside the anchor div or more specifically, -->
    <!-- the w3-row (or grid) there are columns layout: a one-column -->
    <!-- display, a two-column display, a three-column display, etc. -->
    <!-- in this case, we have a three-column layout web site! -->

    <!-- Left Column -->

    <!-- this is the left column in the web site: see profile area column! -->
    <!-- m3 is short for medium 3 out of 12 columns: 3-twelfth of the grid -->

    <!-- W3Schools uses three sizes: small (s), medium (m), large (l) -->
    <!-- so if you see s1 means a small scale grid with one-twelfth of -->
    <!-- the grid. m7 is a medium scale layout with 7/12 of the total -->
    <!-- grid layout. -->

    <!-- likewise, an l2 (that is "L" and 2) means 1arge scale layout-->
    <!-- with a two-twelfth of the total grid layout! -->

    <!-- here, we have a medium scale with 3/12th of the total grid layout -->

    <!-- as you can see, this left column has a class w3-container to hold -->
    <!-- the entire left side area! -->

    <!-- as stated above, class w3-container can be used inside this -->
    <!-- container area as well! sort of containers within container! -->

    <div class="w3-col m3 w3-container">

      <!-- Profile -->

      <!-- w3-card is a class to make the profile looks like a deck -->
      <!-- of cards, w3-round will make the deck of cards rounded -->
      <!-- edges on all 4 corners -->

      <div class="w3-card w3-round w3-light-blue">

        <!-- here is where class w3-container gets used to hold-->
        <!-- a profile area -->

        <div class="w3-container">
          <h4 class="w3-center">My Profile</h4>
            <p class="w3-center"><img src="./image/paul_tuon.jpg"
               class="w3-circle" style="height:106px;width:106px"
               alt="A Profile Picture"></p>
               <hr>
            <p><i class="fa fa-pencil fa-fw w3-margin-right
               w3-text-theme"></i> Designer, UI</p>
            <p><i class="fa fa-home fa-fw w3-margin-right
               w3-text-theme"></i> Minneapolis, MN (US)</p>
            <p><i class="fa fa-birthday-cake fa-fw w3-margin-right
               w3-text-theme"></i> April 1, 2020</p>
        </div>
       </div>
       <br>

<!-- Accordion -->

<!-- this block of code contains an accordion-like feature -->
<!-- when a user clicks on an item it slides down to reveal the content! -->

      <!-- class w3-card is a css that made to look like a deck of cards -->

      <div class="w3-card w3-round">
        <div class="w3-pale-blue">

          <!-- when a user clicks on "My Groups" it calls myFunction() -->
          <!-- and it displays an accordion style revealing the content -->

          <!-- you might want to experiment using other elements such -->
          <!-- as div or span or other elements instead of button! -->

          <button onclick="myFunction('Demo1')" class="w3-button
             w3-block w3-theme-l1 w3-left-align">
             <i class="fa fa-circle-onotch fa-fw w3-margin-right">
              My Groups</i></button>

          <!-- here is again w3-container gets used! -->

          <!-- note that w3-hide hides the content inside the -->
          <!-- div when the page is loaded! -->

          <!-- it will only reveal the content when a user clicks -->
          <!-- on "My Groups"! -->

          <div id="Demo1" class="w3-hide w3-container">
             <p>Some text..</p>
          </div>

          <!-- when a user clicks on "My Events" it calls myFunction() -->
          <!-- and it displays an accordion style calendar of events -->
          <!-- by sliding down to reveal the content -->

          <!-- you might want to experiment using other elements such -->
          <!-- as div or span or other elements instead of button! -->

          <!-- right here where you might want to place a break: "<br>" -->
          <!-- to make the gap between the two accordion item elements! -->

          <!-- so instead of using "<br>" you might want to use -->
          <!-- css styling to specify how much gap you want because -->
          <!-- "<br>" might be bigger/smaller gap than you like! -->

          <!-- so using css to style the gap is probably a good idea! -->

          <button onclick="myFunction('Demo2')" class="w3-button w3-block
             w3-theme-l1 w3-left-align"><i class="fa fa-calendar-check-0
             fa-fw w3-margin-right"> My Events</i></button>

          <!-- here is again w3-container gets used! -->

          <!-- again w3-hide hides the content inside the -->
          <!-- div when the page is loaded! -->

          <!-- it will only reveal the content when a user clicks -->
          <!-- on "My Events"! -->

          <div id="Demo2" class="w3-hide w3-container">
             <p>Some other text..</p>
          </div>

          <!-- likewise, when a user clicks on "My Photos" it calls -->
          <!-- myFunction() and it displays an accordion style album -->
          <!-- of photos by sliding down to reveal the photos in a -->
          <!-- two-column layout -->

          <!-- if you provide photos in the below container: a photo -->
          <!-- album container, it will display them when a user -->
          <!-- clicks on "My Photos" -->

          <!-- you might want to experiment using other elements such -->
          <!-- as div or span or other elements instead of button! -->

          <!-- right here where you might want to place a break: "<br>" -->
          <!-- to make the gap between the two accordion item elements! -->

          <!-- so instead of using "<br>" you might want to use -->
          <!-- css styling to specify how much gap you want because -->
          <!-- "<br>" might be bigger/smaller gap than you like! -->

          <!-- so using css to style the gap is probably a good idea! -->

          <button onclick="myFunction('Demo3')" class="w3-button
             w3-block w3-theme-l1 w3-left-align">
             <i class="fa fa-user fa-fw w3-margin-right"> My Photos
             </i></button>

          <!-- class w3-container is used to hold the photos album layout -->
          
          <!-- w3-hide is a class to hide the element: diplay: none -->
          <!-- as you can see, when the web site is loaded, "Demo3" is -->
          <!-- not shown! -->
          <!-- it will only be shown when a user clicks on -->
          <!-- "My Photos" button! -->

          <div id="Demo3" class="w3-hide w3-container">
            <div class="w3-row-padding">
               <br>

               <!-- the following is where you put your photo album! -->

               <!-- class w3-half is a grid layout as a two-column -->
               <!-- layout relative to the class w3-container used -->
               <!-- in the album layout so the photos are arranged -->
               <!-- side by side as a two-column layout -->

               <div class="w3-half">
                  <img src="./image/paul_tuon.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <div class="w3-half">
                  <img src="./image/graduation.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <!-- this is another two-column grid stacking below above -->

               <div class="w3-half">
                  <img src="./image/paul_tuon.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <div class="w3-half">
                  <img src="./image/graduation.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <!-- this is another two-column grid stacking below above -->

               <div class="w3-half">
                  <img src="image/example5.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <div class="w3-half">
                  <img src="image/graduation.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>
            </div>  <!-- end div class="w3-row-padding" -->
          </div>  <!-- end div id="Demo3" -->
        </div>  <!-- end div class="w3-white" -->
      </div>  <!-- end div class="w3-card w3-round" -->

<!-- this is the end of an accordion-like feature! -->

<!-- at this point there are still 3 open div -->

<!-- Interest: the miscellaneous content of interest! -->

<!-- w3-hide-small is to not display the content when mobile -->
<!-- device is used to load the web site! so "Interests" content -->
<!-- won't be loaded if mobile device is being used to load -->
<!-- this web site -->

<div class="w3-card w3-round w3-teal w3-hide-small">
   <div class="w3-container">
      <p>Interests</p>

      <p>
         <span class="w3-tag w3-small w3-theme-d5">News</span>
         <span class="w3-tag w3-small w3-theme-d4">W3Schools</span>
         <span class="w3-tag w3-small w3-theme-d3">Labels</span>
         <span class="w3-tag w3-small w3-theme-d2">Games</span>
         <span class="w3-tag w3-small w3-theme-d1">Friends</span>
         <span class="w3-tag w3-small w3-theme">Games</span>
         <span class="w3-tag w3-small w3-theme-l1">Friends</span>
         <span class="w3-tag w3-small w3-theme-l2">Food</span>
         <span class="w3-tag w3-small w3-theme-l3">Design</span>
         <span class="w3-tag w3-small w3-theme-l4">Art</span>
         <span class="w3-tag w3-small w3-theme-l5">Photos</span>
      </p>
   </div>
</div>

The following block of code contained in the original template

<!-- Alert box -->

<!-- when a user clicks on this div area an alert box pops up -->
<!--
<div class="w3-container w3-display-container w3-round w3-theme-14
   w3-border w3-theme-border w3-margin-bottom w3-hide-small w3-red">
   <span onclick="this.parentElement.style.display='none'"
      class="w3-button w3-theme-13 w3-display-topright">
      <i class="fa fa-remove"></i>
   </span>

   <p><strong>Hey,</strong></p>

   <p>People are looking at your profile. Find out who!</p>
</div>
-->

</div> <!-- end left column -->

<!-- at this point there are still 2 open <div> tags -->

<!-- start middle column -->

<!-- this is the start of the middle column. -->
<!-- size m7 means 7/12 of the grid -->
<!-- as you can figure it out: there are 12 columns in the entire grid -->
<!-- if the left side column is m3, meaning 3/12 of the grid, -->
<!-- and middle column is 7/12 of the grid, -->
<!-- the right column has to be 2/12 of the grid! -->

<div class="w3-col m7">

  <!-- right here where I add some new content to the middle column -->

  <!-- I add a scrolling message board to make it more flashy. for example: -->

  <div class="w3-row-padding">

    <!-- notice that you need to use the entire length of the grid: m12 -->
    <!-- meaning the entire middle column -->

    <div class="w3-col m12">

    <div class="w3-card-2 w3-round w3-white">
      <div class="w3-container w3-padding">

         <marquee bgcolor=white width="100%" height="50">
            <font size="5" color="#FF66FF">
            Welcome to the 21st century and beyond where digital mobile rules!</font>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <font size="5" color="#1883FF">More content to scroll!</font>
         </marquee>

     </div>
    </div>
   </div>
  </div>

   <div class="w3-row-padding">
      <div class="w3-col m12">
         <div class="w3-card w3-round w3-white">
            <div class="w3-container w3-padding">
               <h6 class="w3-opacity">Social Media Template</h6>
                  <p contenteditable="true" class="w3-border
                      w3-padding">Status: Feeling blue!</p>
                  <button type="button" class="w3-button w3-theme">
                       <i class="fa fa-pencil"></i> Post
                  </button>
             </div>
          </div>
       </div>
    </div>

    <div class="w3-container w3-card w3-round w3-blue w3-margin">
      <img src="./image/paul_tuon.jpg" alt="Avatar" class="w3-left
              w3-circle w3-margin-right" style="width:60px">
      <span class="w3-right w3-opacity">1 min</span>

      <h4>John Doe</h4>

      <hr class="w3-clear">

      <p>This is just an ordinary content! You can put whatever
            content you want!</p>

      <div class="w3-row-padding" style="margin:0 -16px">
         <!-- 
         <div class="w3-half">
            <img src="./image/graduation.jpg" alt="just a picturer"
                    style="width: 100%" class="w3-margin-bottom">
         </div>

         <div class="w3-half">
            <img src="./image/paul_tuon.jpg" alt="another picture"
                    style="width: 100%" class="w3-margin-bottom">
         </div>
         -->
      </div>

      <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom">
            <i class="fa fa-thumbs-up"></i> Like</button>
      <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom">
            <i class="fa fa-comment"></i> Comment</button>
    </div>

    <div class="w3-container w3-card w3-round w3-khaki w3-margin"><br>
       <!--
       <img src="./image/graduation.jpg" alt="Avatar" class="w3-left
               w3-circle w3-margin-right" style="width:60px">
       -->
       <span class="w3-right w3-opacity">16 min</span>

       <h4>Jane Doe</h4>

       <hr class="w3-clear">

       <p>Lorem ipsum dolor. Lorem ipsum dolor. Lorem ipsum dolor.
             Lorem ipsum dolor. Lorem ipsum dolor.</p>

       <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom">
             <i class="fa fa-thumbs-up"></i> Like</button>
       <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom">
             <i class="fa fa-comment"></i> Comment</button>
    </div>

The following block of code contained in the original template

<!--

    <div class="w3-container w3-card w3-round w3-lime w3-margin"><br>

       <img src="./image/paul_tuon.jpg" alt="Avatar" class="w3-left
          w3-circle w3-margin-right" style="width:60px">

       <span class="w3-right w3-opacity">30 min</span>

       <h4>Angie Jane

       <hr class="w3-clear">

       <img src="./image/gradution.jpg" class="w3-margin-bottom"
               style="width:100%">

       <p>Lorem ipsum dolor. Lorem ipsum dolor. Lorem ipsum dolor.
             Lorem ipsum dolor. Lorem ipsum dolor.</p>

       <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom">
             <i class="fa fa-thumbs-up"></i> Like</button>
       <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom">
             <i class="fa fa-comment"></i> Comment</button>
    </div>
-->


<!-- on the left side column there is an accordion slide down/up -->
<!-- feature which contains three sections: My Groups, My Events, -->
<!-- My Photos! you can use that code example to place your -->
<!-- accordion feature anywhere on the website! -->

<!-- let's put that same accordion feature in the middle column at -->
<!-- the very bottom just before the start of the footer! -->

<!-- just remember that each accordion item must contains -->
<!-- a unique id, e.g., group, event, photo! -->

<!-- start accordion style feature! -->

<!-- Accordion -->

      <div class="mobile-card mobile-round">
        <div class="mobile-pale-blue">

          <!-- when a user clicks on "My Groups" it will call -->
          <!-- myFunction() and it displays an accordion -->
          <!-- style revealing the content -->

          <!-- you might want to experiment using other elements such -->
          <!-- as div or span or other elements instead of button! -->

          <button onclick="myFunction('group')"
              class="mobile-button mobile-block mobile-theme-l1
              mobile-left-align">
              <i class="fa fa-circle-onotch fa-fw
              mobile-margin-right"> My Groups</i>
          </button>

          <div id="group" class="mobile-hide mobile-container">
              <p>Some text..</p>
          </div>

          <!-- when a user clicks on "My Events" it will call -->
          <!-- myFunction() and it displays an accordion -->
          <!-- style calendar of events by sliding down to -->
          <!-- reveal the content! -->

          <!-- you might want to experiment using other elements such -->
          <!-- as div or span or other elements instead of button! -->

          <button onclick="accordion('event')"
             class="mobile-button mobile-block mobile-theme-l1
             mobile-left-align">
             <i class="fa fa-calendar-check-0 fa-fw
             mobile-margin-right"> My Events</i>
          </button>

          <div id="event" class="mobile-hide mobile-container">
              <p>Some other text..</p>
          <div>

          <!-- likewise, when a user clicks on "My Photos" it calls -->
          <!-- myFunction() and it displays an accordion style -->
          <!-- album of photos by sliding down to reveal the photos -->
          <!-- in a two-column layout -->

          <!-- if you provide photos in the below container: a photo -->
          <!-- album container! it will display them when a user -->
          <!-- clicks on "My Photos" -->

          <!-- the below layout is a two-column layout displaying -->
          <!-- two photos side by side! -->
          <!-- in this example, there are six photos displaying -->
          <!-- in pairs to make it three rows! -->

          <!-- you might want to experiment using other elements such -->
          <!-- as div or span or other elements instead of button! -->

          <span class="hljs-string"><button onclick="accordion('photo')"
                class="mobile-button mobile-block mobile-theme-l1
                mobile-left-align"><i class="fa fa-user
                fa-fw mobile-margin-right"> My Photos</i>
          </button>

          <div id="photo" class="mobile-hide mobile-container">
            <div class="mobile-row-padding">
               <br>

               <div class="mobile-half">
                  <img src="./image/paul_tuon.jpg" style="width: 100%"
                  class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="./image/paul_tuon_graduation.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="./image/paul_tuon.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="./image/paul_tuon_graduation.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="image/paul_tuon.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="image/paul_tuon_graduation.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>
            </div>  <!-- end div class="mobile-row-padding" -->
          </div>  <!-- end div id="photo" -->
        </div>  <!-- end div class="mobile-pale-blue" -->
      </div>  <!-- end div class="mobile-card mobile-round" -->

   <!-- end accordion style feature! -->

</div> <!-- end middle column -->

<!-- start right column -->

<!-- here it is: right column is 2/12 of the grid -->

<div class="w3-col m2">
   <div class="w3-card w3-round w3-aqua w3-center">
      <div class="w3-container">
         <p>Upcoming Events:</p>

         <img src="./image/image_105.jpg" class="w3-margin-bottom"
                 style="width:100%">

         <p><strong>Holiday</strong></p>
         <p>Friday 15:00</p>
         <p><button type="button" class="w3-button w3-theme-14
            w3-block">Info</button></p>
      </div>
    </div>

    <div class="w3-card w3-round w3-pink w3-center">
      <iv class="w3-container">
         <p>Friend Request</p>
         <!--
         <img src="./image/graduation.jpg" class="w3-margin-bottom"
                 style="width:50%">
         -->
         <span>Jane Doe</span>
         <div class="w3-row w3-opacity">

           <div class="w3-half">
              <button type="button" class="w3-button w3-block-14
              w3-green w3-section" title="Accept">
              <i class="fa fa-check"></i></button>
           </div>

           <div class="w3-half">
              <button type="button" class="w3-button w3-block-14
              w3-red w3-section" title="Decline">
              <i class="fa fa-remove"></i></button>
           </div>
         </div>
       </div>
    </div>
    <br>

    <div class="w3-card w3-round w3-purple w3-padding w3-center">
       <p>ADS</p>
    </div>
    <br>
</div> <!-- end right column -->

<!-- here is the closing div for class w3-row! -->

</div> <!-- end grid containing class w3-row -->

<!-- right here, if you have more table rows-like data content, -->
<!-- you can add another div containing a class w3-row -->

<!-- after all the data content for this particular row has been -->
<!-- included, you can close out this div containing class w3-row -->

<!-- you can keep repeating this pattern over and over as you -->
<!-- need to make your website looks like table rows-like content! -->

<!-- the rows have to be inside the closing of the div that -->
<!-- contains w3-container! -->

<!-- here is the closing div that contains class w3-container! -->

</div> <!-- end page container -->

<!-- at this point all open div tags have been closed -->


<!-- so the grid system is very simple. -->
<!-- it only contains two classes: w3-container and w3-row -->
<!-- that's all! -->

<!-- anything inside the grid are just ordinary html elements: -->
<!-- div, p, span, etc. -->
<!-- as you can see from the above grid, -->
<!-- it contains only one w3-container and one w3-row -->
<!-- that's all! -->

<!-- here is the last section of the website: footer -->

<!-- start footer -->

<footer class="w3-container w3-theme-d3 w3-padding-16">
   <div>Follow us on social medias: Facebook, Twitter, Instagram!</div>
   <div class="w3-right">Contact: john@doe.com</div>
</footer>


<script>
// Accordion
function myFunction(id)
    {
     var x = document.getElementById(id);
     if (x.className.indexOf("w3-show") == -1)
        {
         x.className += " w3-show";
         x.previousElementSibling.className += " w3-theme-d1";
        }
     else
        {
         x.className = x.className.replace("w3-show", "");
         x.previousElementSibling.className =
         x.previousElementSibling.className.replace(" w3-theme-d1", "");
        }
    }


// used to toggle on smaller screen when clicking on the menu button
function openNav()
    {
     var x = document.getElementById("navDemo");
     if (x.className.indexOf("w3-show") == -1)
        {
         x.className += " w3-show";
        }
     else
        {
         x.className = x.className.replace(" w3-show", "");
        }
    }
</script>

</body>
</html>


/* Here is the listing of colors. see css file for more definitions */

/* Colors */

.w3-amber, .w3-hover-amber:hover{color:#000!important;
          background-color:#ffc107!important}
.w3-aqua,.w3-hover-aqua:hover{color:#000!important;
          background-color:#00ffff!important}
.w3-blue,.w3-hover-blue:hover{color:#fff!important;
          background-color:#2196F3!important}
.w3-light-blue,.w3-hover-light-blue:hover{color:#000!important;
          background-color:#87CEEB!important}
.w3-brown,.w3-hover-brown:hover{color:#fff!important;
         background-color:#795548!important}
.w3-cyan,.w3-hover-cyan:hover{color:#000!important;
         background-color:#00bcd4!important}
.w3-blue-grey,.w3-hover-blue-grey:hover,.w3-blue-gray,
.w3-hover-blue-gray:hover{color:#fff!important;
         background-color:#607d8b!important}
.w3-green,.w3-hover-green:hover{color:#fff!important;
         background-color:#4CAF50!important}
.w3-light-green,.w3-hover-light-green:hover{color:#000!important;
         background-color:#8bc34a!important}
.w3-indigo,.w3-hover-indigo:hover{color:#fff!important;
         background-color:#3f51b5!important}
.w3-khaki,.w3-hover-khaki:hover{color:#000!important;
         background-color:#f0e68c!important}
.w3-lime,.w3-hover-lime:hover{color:#000!important;
         background-color:#cddc39!important}
.w3-orange,.w3-hover-orange:hover{color:#000!important;
         background-color:#ff9800!important}
.w3-deep-orange,.w3-hover-deep-orange:hover{color:#fff!important;
         background-color:#ff5722!important}
.w3-pink,.w3-hover-pink:hover{color:#fff!important;
         background-color:#e91e63!important}
.w3-purple,.w3-hover-purple:hover{color:#fff!important;
         background-color:#9c27b0!important}
.w3-deep-purple,.w3-hover-deep-purple:hover{color:#fff!important;
         background-color:#673ab7!important}
.w3-red,.w3-hover-red:hover{color:#fff!important;
         background-color:#f44336!important}
.w3-sand,.w3-hover-sand:hover{color:#000!important;
         background-color:#fdf5e6!important}
.w3-teal,.w3-hover-teal:hover{color:#fff!important;
         background-color:#009688!important}
.w3-yellow,.w3-hover-yellow:hover{color:#000!important;
         background-color:#ffeb3b!important}
.w3-white,.w3-hover-white:hover{color:#000!important;
         background-color:#fff!important}
.w3-black,.w3-hover-black:hover{color:#fff!important;
         background-color:#000!important}
.w3-grey,.w3-hover-grey:hover,.w3-gray,
.w3-hover-gray:hover{color:#000!important;
         background-color:#9e9e9e!important}
.w3-light-grey,.w3-hover-light-grey:hover,.w3-light-gray,
.w3-hover-light-gray:hover{color:#000!important;
         background-color:#f1f1f1!important}
.w3-dark-grey,.w3-hover-dark-grey:hover,.w3-dark-gray,
.w3-hover-dark-gray:hover{color:#fff!important;
         background-color:#616161!important}
.w3-pale-red,.w3-hover-pale-red:hover{color:#000!important;
         background-color:#ffdddd!important}
.w3-pale-green,.w3-hover-pale-green:hover{color:#000!important;
         background-color:#ddffdd!important}
.w3-pale-yellow,.w3-hover-pale-yellow:hover{color:#000!important;
         background-color:#ffffcc!important}
.w3-pale-blue,.w3-hover-pale-blue:hover{color:#000!important;
         background-color:#ddffff!important}

.w3-text-amber,.w3-hover-text-amber:hover{color:#ffc107!important}
.w3-text-aqua,.w3-hover-text-aqua:hover{color:#00ffff!important}
.w3-text-blue,.w3-hover-text-blue:hover{color:#2196F3!important}
.w3-text-light-blue,.w3-hover-text-light-blue:hover{color:#87CEEB!important}
.w3-text-brown,.w3-hover-text-brown:hover{color:#795548!important}
.w3-text-cyan,.w3-hover-text-cyan:hover{color:#00bcd4!important}
.w3-text-blue-grey,.w3-hover-text-blue-grey:hover,.w3-text-blue-gray,
.w3-hover-text-blue-gray:hover{color:#607d8b!important}
.w3-text-green,.w3-hover-text-green:hover{color:#4CAF50!important}
.w3-text-light-green,.w3-hover-text-light-green:hover{color:#8bc34a!important}
.w3-text-indigo,.w3-hover-text-indigo:hover{color:#3f51b5!important}
.w3-text-khaki,.w3-hover-text-khaki:hover{color:#b4aa50!important}
.w3-text-lime,.w3-hover-text-lime:hover{color:#cddc39!important}
.w3-text-orange,.w3-hover-text-orange:hover{color:#ff9800!important}
.w3-text-deep-orange,.w3-hover-text-deep-orange:hover{color:#ff5722!important}
.w3-text-pink,.w3-hover-text-pink:hover{color:#e91e63!important}
.w3-text-purple,.w3-hover-text-purple:hover{color:#9c27b0!important}
.w3-text-deep-purple,.w3-hover-text-deep-purple:hover{color:#673ab7!important}
.w3-text-red,.w3-hover-text-red:hover{color:#f44336!important}
.w3-text-sand,.w3-hover-text-sand:hover{color:#fdf5e6!important}
.w3-text-teal,.w3-hover-text-teal:hover{color:#009688!important}
.w3-text-yellow,.w3-hover-text-yellow:hover{color:#d2be0e!important}
.w3-text-white,.w3-hover-text-white:hover{color:#fff!important}
.w3-text-black,.w3-hover-text-black:hover{color:#000!important}
.w3-text-grey,.w3-hover-text-grey:hover,.w3-text-gray,
.w3-hover-text-gray:hover{color:#757575!important}
.w3-text-light-grey,.w3-hover-text-light-grey:hover,
.w3-text-light-gray,.w3-hover-text-light-gray:hover{color:#f1f1f1!important}
.w3-text-dark-grey,.w3-hover-text-dark-grey:hover,
.w3-text-dark-gray,.w3-hover-text-dark-gray:hover{color:#3a3a3a!important}

/* can you make sense of the above color definitions? */

/* let's take the last color definition above: the last line! */

.w3-text-dark-gray,.w3-hover-text-dark-gray:hover{color:#3a3a3a!important}

/* format it like this for a better visualization: */

.w3-text-dark-gray,
.w3-hover-text-dark-gray:hover
    {
     color:#3a3a3a!important
    }

/* there are two classes: one is w3-text-dard-gray and the other */
/* is w3-hover-text-dark-gray which is attached to a hover mouse event. */
/* both of these two classes are assigned a color of a dark-gray */
/* which is #3a3a3a */
/* disregard the word "!important" for now. you can learn more in */
/* the css tutorial provided by W3Schools */

/* if you decide to add your own css definition, just add them to */
/* the bottom of the w3.css file. */

/* for example, if you find that the pre-made colors provided by */
/* W3Schools are not enough to your liking, you can add more color */
/* definitions to w3.css file like this: */

.w3-slate-gray
    {
     /** don't forget to put "!important" as well! **/
     color:#ebe2e1!important
    }

/* you can add other definitions to w3.css file as well because */
/* w3.css is only a css file framework that contains the universal */
/* commonly used definitions. */
/* so you most certainly need to add your own css defitions to */
/* the w3.css file */

/* A SECRET TO MEMORIZING CSS ATTRIBUTES or PROPERTIES */

/* one of the most confusing things in CSS is memorizing */
/* attributes/properties */

/* what if you have an attribute that says: */
/* padding: 10px 5px 20px 10px */

/* what does that mean? */

/* it means the padding property has four values:

   top padding is 10px
   right padding is 5px
   bottom padding is 20px
   left padding is 10px
*/

/* so how do you remember them? */
/* by brute force? */
/* that's what most people do: remembering it by brute force! */

/* but there is an easier way to remembering them and here's how: */

/* first, think of all HTML elements as a box. well, to be honest */
/* all HTML elements (div, p, span, a, button, i, etc) are boxes! */
/* and boxes have four sides and four corners! */

/* when you style an HTML element using padding you actually are */
/* styling the four sides and four corners! */
/* if you follow the definition above it says padding 10px 5px 20px 10px */

/* it basically tells you to follow the box sitting stationary upright */
/* starting from the top of the box, which is 10px in height, and */
/* then follow the box around, which is to the right side of the box! */

/* in the right side of the box is where you find a 5px wide space gap! */
/* now you're done with the right side of the box, so you continue on */
/* around the box, which is to the bottom of the box containing 20px in */
/* height! */

/* now you're at the bottom of the box and you continue to follow */
/* the box around, which is to the left side of the box containing */
/* a 10px wide gap! */

/* There you have it! a secret to memorizing the CSS attributes! */

/* what if you have something like the following illustrations? */
/* the same thing: follow the box! well, sort of! but you get the idea!

if the padding property has three values:

   padding: 25px 50px 75px;

   top padding is 25px
   right and left paddings are 50px
   bottom padding is 75px

above, start at the top of the box and move to the right side of the box!
now since right and left are together, it is a common value for both!

from there, you continue on around the box until all four sides are met!

if the padding property has two values:

   padding: 25px 50px;

   top and bottom paddings are 25px
   right and left paddings are 50px

this is where the rule is broken and makes an exception, but still not
too far from the rule!

top and bottom go together and right and left also go together!
as you can see, you follow the same box rule logic!

if the padding property has one value:

   padding: 25px;

   all four paddings are 25px

this one is not obvious to the human eyes but the browsers style it
using the box rule by first styling the top and then the right and
then the bottom and finally the left side of the box!
*/

/* YOUR OWN CSS DEFINITIONS */

/* most likely you will need to create your own CSS definitions */
/* to fullfil your needs! */

/* when you create your own definitions make sure that you use your */
/* own prefix and not the 'w3' prefix so that to avoid conflict! */

/* the color, padding, margin size, and text size are probably the */
/* most definitions you might need to create to fullfil your needs! */

/* for example, in most cases, you might need to style the left side */
/* margin only by using a 'my-padding-left-10 or my-margin-left-20 or
   whatever margin or padding size you need!

   .my-padding-left-10
       {
        /* here is where you specify the size */
        padding-left:10px!important;
       }

   .my-margin-left-20
       {
        /* here is where you specify the size */
        margin-left:20px!important;
       }
*/

/* there you have it! */
/* please check out tutorials at the W3Schools.com for more */
/* on this topic! */

For more about colors, please see my tutorial called an introduction to colors!

To get your own color check this out: color picker!

As mentioned earlier, the best place to advance your programming skills is the W3Schools. One particular topic that you might want to spend some time on learning is the image tutorial. You can learn how to place background images on your website as well as learning how to make your images work on mobile devices. So there are lots of topics available for you to improve your programming skills.

While you're at it learning about images, you might want to spend some time learning this important CSS class that makes displaying images awesome. The CSS class is called "clearfix" and can be found here: https://www.w3schools.com/howto/howto_css_clearfix.asp

Also, while you're at it learning about CSS, you might find these topics interesting and useful as well. Check the following topics out:

Best Free JavaScript & CSS/CSS3 Libraries For Modern Web Design

Spinners & Progress Bars

For more good stuffs, particularly photo galleries, sliders and plugins, please check out this site called https://www.jqueryscript.net/

There you have it! So go at it!!!

Incorporate Photo Slider in a Website for Beginners

First, you need to visit the jqueryscript.net mentioned above and browse through their sliders. Once you've decided which one you want, go ahead and download their plugin and go from there. Each plugin has a demo for you to see a preview of what it should look like. It also has a tutorial to help you incorporate it in your website.

For this tutorial, I chose one of the jquery slider plugin that I found on the Internet and it is called CarouFredSel. Here is the link to that plugin: https://github.com/DivaVocals/carouFredSel

If you want to use this plugin, you need to download the plugin from the link mentioned above and extract it. The plugin as usual comes in a zip package, so you definitely need a zip software installed on your computer to extract it. See instruction on zip application earlier at the beginning of this tutorial.

Once you'd downloaded and extracted it, you can view the demo contains in file index.html inside the main folder called 'carouFredSel-master'. Just double-click on the file index.html and it will activate a demo screen showing the various styles of the slider that you can use to incorporate in your own website.

Let's incorporate that plugin in the example website shown above.

File: index.php

<!DOCTYPE html>
<html>
<head>
<title>Template</title>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- include jQuery + carouFredSel plugin -->

<!-- right here where you link to a jquery library that -->
<!-- is hosted in a Content Delivery Network or CDN -->

<!-- a CDN is just a central data network that mainly delivering -->
<!-- data content to users via a link! -->

<script type="text/javascript" language="javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<!-- this CDN is owned by Google! -->
<!-- so Google is hosting the jquery library for everyone to link to -->
<!-- and use it instead of embedding that jquery library in their own script! -->

<!-- personally, I recommend that you embedd jquery library in your own -->
<!-- script instead of linking to a CDN! -->

<!-- to embedd a jquery library in your own script, do like the following -->
<!-- assuming you'd downloaded the jquery and place that library in a folder -->
<!-- called js/jquery -->

<script type="text/javascript" language="javascript"
src="js/jquery/jquery.min.js"></script>

<!-- to download the jquery library you -->
<!-- need to go to the jquery website: -->
<!-- https://jquery.com/download/ -->

<!-- click on the "Download the compressed, production" -->
<!-- and just hilight the whole file content and -->
<!-- copy and paste it in a blank file and name it accordingly! -->

<!-- in my case above, I named the jquery library file name to -->
<!-- 'jquery.min.js'  -->

<!-- do not include both the CDN and the embedded library at the -->
<!-- same time because it might cause problems! -->
<!-- so use one or the other and not both of them at the same time! -->

<!-- next is the link to the carouFredSel library stored in the -->
<!-- plugin folder called carouFredSel-master -->

<script type="text/javascript" language="javascript"
src="jquery.carouFredSel-6.2.1-packed.js"></script>

<!-- optionally include helper plugins -->

<script type="text/javascript" language="javascript"
src="helper-plugins/jquery.mousewheel.min.js"></script>

<script type="text/javascript" language="javascript"
src="helper-plugins/jquery.touchSwipe.min.js"></script>

<script type="text/javascript" language="javascript"
src="helper-plugins/jquery.transit.min.js"></script>

<script type="text/javascript" language="javascript"
src="helper-plugins/jquery.ba-throttle-debounce.min.js"></script>

<link rel="stylesheet" href="./css/mobile.css">

<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/
                                        css/font-awesome.min.css">
<link rel="stylesheet"
      href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/
                                        3.2.0/css/bootstrap.min.css">

<script src="https://code.jquery.com/w3/1.4.5/jquery.w3-1.4.5.min.js">
</script>

<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="javascript/javascript.js">
</script>

<!-- start plugin onDocumentReady -->

<script type="text/javascript" language="javascript">

$(function()
      {
       // Responsive layout, resizing the items
       $('#foo4').carouFredSel(
                               {
                                responsive: true,
                                width: '100%',
                                scroll: 2,
                                items:
                                     {
                                      // the sliding content's width
                                      // if you set it to half the
                                      // screen size it will show two
                                      // images at a time.

                                      // if you set it to full screen
                                      // (1000 pixels) it will show one
                                      // image at a time.

                                      width: 400,

                                      // commenting out the optionally
                                      // resize item-height option
                                      // height: '30%',

                                      visible:
                                             {
                                              min: 2,
                                              max: 6
                                             }
                                     }
                               }
                              );
      }
</script>

<style type="text/css" media="all">
.list_carousel
     {
      background-color: #ccc;
      margin: 0 0 30px 60px;
      width: 360px;
     }

.list_carousel ul
     {
      margin: 0;
      padding: 0;
      list-style: none;
      display: block;
     }

.list_carousel li
     {
      font-size: 40px;
      color: #999;
      text-align: center;
      background-color: #eee;
      border: 5px solid #999;
      width: 50px;
      height: 50px;
      padding: 0;
      margin: 6px;
      display: block;
      float: left;
     }

.list_carousel.responsive
     {
      width: auto;
      margin-left: 0;
     }

.clearfix
     {
      float: none;
      clear: both;
     }

.prev
     {
      float: left;
      margin-left: 10px;
     }

.next
     {
      float: right;
      margin-right: 10px;
     }
</style>
</head>

<body class="w3-theme-l5 w3-light-grey">

<!-- some of the following codes were broken down into multiple lines -->
<!-- to fit the screen display -->

<!-- Navbar -->

<!-- this is the div that wraps around the navbar -->

<div class="w3-top">

  <div class="w3-bar w3-theme-d2 w3-left-align w3-small w3-blue">
     <a class="w3-bar-item w3-button w3-hide-medium w3-hide-large w3-right
                  w3-padding-small w3-hover-white w3-small w3-theme-d2"
                  href="javascript:void(0);" onclick="openNav()">
                  <i class="fa fa-bars"></i></a>

    <a href="#" class="w3-bar-item w3-button w3-padding-large w3-theme-d4">
                   <i class="fa fa-home w3-margin-right"></i>Logo</a>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large
                   w3-hover-white" title="News"><i class="fa fa-globe"></i></a>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large
        w3-hover-white" title="Account Settings"><i class="fa fa-user"></i></a>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large
               w3-hover-white" title="Messages"><i class="fa fa-envelope"></i>

    <div class="w3-dropdown-hover w3-hide-small">
      <button class="w3-button w3-padding-large" title="Notifications">
           <i class="fa fa-bell"></i>
           <span class="w3-badge w3-right w3-small w3-green">3</span>
      </button>

      <div class="w3-dropdown-content w3-card-4 w3-bar-block"
              style="width:300px">
         <a href="#" class="w3-bar-item w3-button">One new friend request</a>
         <a href="#" class="w3-bar-item w3-button">John Doe posted on
              your wall</a>
         <a href="#" class="w3-bar-item w3-button">Jane likes your post</a>
      </div>
    </div>

    <a href="#" class="w3-bar-item w3-button w3-hide-small w3-right
       w3-padding-medium w3-hover-white" title="My Account">
       <img src="./image/paul_tuon.jpg" class="w3-circle"
       style="height:23px;width:23px" alt="Avatar"> </a>
  </div>

</div> <!-- end div class="w3-top" -->

<!-- Navbar on small screens -->

<div id="navDemo" class="w3-bar-block w3-theme-d2 w3-hide
   w3-hide-large w3-hide-medium w3-large">
   <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 1</a>
   <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 2</a>
   <a href="#" class="w3-bar-item w3-button w3-padding-large">Link 3</a>
   <a href="#" class="w3-bar-item w3-button w3-padding-large">My Profile</a>
</div>

<!-- now the navbar code is done! -->

<!-- at this point there are 0 open <div> tag -->


<!-- Slider Container -->

<div class="w3-container w3-content" style="max-width:1400px; margin-top:40px">
   <div class="list_carousel responsive">

      <!-- right here where the content of the slider is placed -->
      <!-- notice that you can put any kind of content such as -->
      <!-- text, images, etc., and as many content as you wish! -->
      <!-- the slider will circle through the content until the end and loops -->
      <!-- back to the beginning of the list! -->

      <!-- the display of the images is dependenced on the size of the window -->
      <!-- you set in the options of the function carouFredSel() above! -->
      <!-- in the example above it was set to width: 400! -->

      <ul id="foo4">
         <li><img src="image/picture1.jpg"></li>
         <li><img src="image/picture2.jpg"></li>
         <li><img src="image/picture3.jpg"></li>
         <li><img src="image/picture4.jpg"></li>
         <li><img src="image/picture5.jpg"></li>
         <li><img src="image/picture6.jpg"></li>
         <li><img src="image/picture7.jpg"></li>
         <li><img src="image/picture8.jpg"></li>
         <li><img src="image/picture9.jpg"></li>
         <li><img src="image/picture10.jpg"></li>
         <li><img src="image/picture11.jpg"></li>
         <li><img src="image/picture12.jpg"></li>
         <li><img src="image/picture13.jpg"></li>
         <li><img src="image/picture14.jpg"></li>
         <li><img src="image/picture15.jpg"></li>
         <li><img src="image/picture16.jpg"></li>
      </ul>

      <!-- for more tutorial on class "clearfix" please visit -->
      <!-- https://www.w3schools.com/howto/howto_css_clearfix.asp -->

      <div class="clearfix"></div>

   </div>
</div>


<!-- Page Container -->

<div class="w3-container w3-content" style="max-width:1400px; margin-top:80px">

  <!-- The Grid -->

  <!-- here is the row! -->

  <div class="w3-row">

    <!-- Left Column -->

    <div class="w3-col m3 w3-container">

      <!-- Profile -->

      <div class="w3-card w3-round w3-light-blue">

        <div class="w3-container">
          <h4 class="w3-center">My Profile</h4>
            <p class="w3-center"><img src="./image/paul_tuon.jpg"
               class="w3-circle" style="height:106px;width:106px"
               alt="A Profile Picture"></p>
               <hr>
            <p><i class="fa fa-pencil fa-fw w3-margin-right
               w3-text-theme"></i> Designer, UI</p>
            <p><i class="fa fa-home fa-fw w3-margin-right
               w3-text-theme"></i> Minneapolis, MN (US)</p>
            <p><i class="fa fa-birthday-cake fa-fw w3-margin-right
               w3-text-theme"></i> April 1, 2020</p>
        </div>
       </div>
       <br>

<!-- Accordion -->

      <div class="w3-card w3-round">
        <div class="w3-pale-blue">

          <button onclick="myFunction('Demo1')" class="w3-button
             w3-block w3-theme-l1 w3-left-align">
             <i class="fa fa-circle-onotch fa-fw w3-margin-right">
              My Groups</i></button>

          <div id="Demo1" class="w3-hide w3-container">
             <p>Some text..</p>
          </div>

          <button onclick="myFunction('Demo2')" class="w3-button w3-block
             w3-theme-l1 w3-left-align"><i class="fa fa-calendar-check-0
             fa-fw w3-margin-right"> My Events</i></button>

          <div id="Demo2" class="w3-hide w3-container">
             <p>Some other text..</p>
          </div>

          <button onclick="myFunction('Demo3')" class="w3-button
             w3-block w3-theme-l1 w3-left-align">
             <i class="fa fa-user fa-fw w3-margin-right"> My Photos
             </i></button>

          <!-- class w3-container is used to hold the photos album layout -->
          
          <!-- "My Photos" button! -->

          <div id="Demo3" class="w3-hide w3-container">
            <div class="w3-row-padding">
               <br>

               <!-- the following is where you put your photo album! -->

               <!-- class w3-half is a grid layout as a two-column -->
               <!-- layout relative to the class w3-container used -->
               <!-- in the album layout so the photos are arranged -->
               <!-- side by side as a two-column layout -->

               <div class="w3-half">
                  <img src="./image/paul_tuon.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <div class="w3-half">
                  <img src="./image/graduation.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <!-- this is another two-column grid stacking below above -->

               <div class="w3-half">
                  <img src="./image/paul_tuon.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <div class="w3-half">
                  <img src="./image/graduation.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <!-- this is another two-column grid stacking below above -->

               <div class="w3-half">
                  <img src="image/example5.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>

               <div class="w3-half">
                  <img src="image/graduation.jpg" style="width: 100%"
                          class="w3-margin-bottom">
               </div>
            </div>  <!-- end div class="w3-row-padding" -->
          </div>  <!-- end div id="Demo3" -->
        </div>  <!-- end div class="w3-white" -->
      </div>  <!-- end div class="w3-card w3-round" -->

<!-- this is the end of an accordion-like feature! -->

<!-- at this point there are still 3 open div -->

<!-- Interest: the miscellaneous content of interest! -->

<!-- w3-hide-small is to not display the content when mobile -->
<!-- device is used to load the web site! so "Interests" content -->
<!-- won't be loaded if mobile device is being used to load -->
<!-- this web site -->

<div class="w3-card w3-round w3-teal w3-hide-small">
   <div class="w3-container">
      <p>Interests</p>

      <p>
         <span class="w3-tag w3-small w3-theme-d5">News</span>
         <span class="w3-tag w3-small w3-theme-d4">W3Schools</span>
         <span class="w3-tag w3-small w3-theme-d3">Labels</span>
         <span class="w3-tag w3-small w3-theme-d2">Games</span>
         <span class="w3-tag w3-small w3-theme-d1">Friends</span>
         <span class="w3-tag w3-small w3-theme">Games</span>
         <span class="w3-tag w3-small w3-theme-l1">Friends</span>
         <span class="w3-tag w3-small w3-theme-l2">Food</span>
         <span class="w3-tag w3-small w3-theme-l3">Design</span>
         <span class="w3-tag w3-small w3-theme-l4">Art</span>
         <span class="w3-tag w3-small w3-theme-l5">Photos</span>
      </p>
   </div>
</div>

</div> <!-- end left column -->

<!-- at this point there are still 2 open <div> tags -->

<!-- start middle column -->

<div class="w3-col m7">

  <!-- right here where I add some new content to the middle column -->

  <!-- I add a scrolling message board to make it more flashy. for example: -->

  <div class="w3-row-padding">

    <!-- notice that you need to use the entire length of the grid: m12 -->
    <!-- meaning the entire middle column -->

    <div class="w3-col m12">

    <div class="w3-card-2 w3-round w3-white">
      <div class="w3-container w3-padding">

         <marquee bgcolor=white width="100%" height="50">
            <font size="5" color="#FF66FF">
            Welcome to the 21st century and beyond where digital mobile rules!</font>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <font size="5" color="#1883FF">More content to scroll!</font>
         </marquee>

     </div>
    </div>
   </div>
  </div>
 
   <div class="w3-row-padding">
      <div class="w3-col m12">
         <div class="w3-card w3-round w3-white">
            <div class="w3-container w3-padding">
               <h6 class="w3-opacity">Social Media Template</h6>
                  <p contenteditable="true" class="w3-border
                      w3-padding">Status: Feeling blue!</p>
                  <button type="button" class="w3-button w3-theme">
                       <i class="fa fa-pencil"></i> Post
                  </button>
             </div>
          </div>
       </div>
    </div>

    <div class="w3-container w3-card w3-round w3-blue w3-margin">
      <img src="./image/paul_tuon.jpg" alt="Avatar" class="w3-left
              w3-circle w3-margin-right" style="width:60px">
      <span class="w3-right w3-opacity">1 min</span>

      <h4>John Doe</h4>

      <hr class="w3-clear">

      <p>This is just an ordinary content! You can put whatever
            content you want!</p>

      <div class="w3-row-padding" style="margin:0 -16px">
         <!-- 
         <div class="w3-half">
            <img src="./image/graduation.jpg" alt="just a picturer"
                    style="width: 100%" class="w3-margin-bottom">
         </div>

         <div class="w3-half">
            <img src="./image/paul_tuon.jpg" alt="another picture"
                    style="width: 100%" class="w3-margin-bottom">
         </div>
         -->
      </div>

      <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom">
            <i class="fa fa-thumbs-up"></i> Like</button>
      <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom">
            <i class="fa fa-comment"></i> Comment</button>
    </div>

    <div class="w3-container w3-card w3-round w3-khaki w3-margin"><br>
       <!--
       <img src="./image/graduation.jpg" alt="Avatar" class="w3-left
               w3-circle w3-margin-right" style="width:60px">
       -->
       <span class="w3-right w3-opacity">16 min</span>

       <h4>Jane Doe</h4>

       <hr class="w3-clear">

       <p>Lorem ipsum dolor. Lorem ipsum dolor. Lorem ipsum dolor.
             Lorem ipsum dolor. Lorem ipsum dolor.</p>

       <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom">
             <i class="fa fa-thumbs-up"></i> Like</button>
       <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom">
             <i class="fa fa-comment"></i> Comment</button>
    </div>

The following block of code contained in the original template

<!--

    <div class="w3-container w3-card w3-round w3-lime w3-margin"><br>

       <img src="./image/paul_tuon.jpg" alt="Avatar" class="w3-left
          w3-circle w3-margin-right" style="width:60px">

       <span class="w3-right w3-opacity">30 min</span>

       <h4>Angie Jane

       <hr class="w3-clear">

       <img src="./image/gradution.jpg" class="w3-margin-bottom"
               style="width:100%">

       <p>Lorem ipsum dolor. Lorem ipsum dolor. Lorem ipsum dolor.
             Lorem ipsum dolor. Lorem ipsum dolor.</p>

       <button type="button" class="w3-button w3-theme-d1 w3-margin-bottom">
             <i class="fa fa-thumbs-up"></i> Like</button>
       <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom">
             <i class="fa fa-comment"></i> Comment</button>
    </div>
-->

<!-- Accordion -->

      <div class="mobile-card mobile-round">
        <div class="mobile-pale-blue">

          <button onclick="myFunction('group')"
              class="mobile-button mobile-block mobile-theme-l1
              mobile-left-align">
              <i class="fa fa-circle-onotch fa-fw
              mobile-margin-right"> My Groups</i>
          </button>

          <div id="group" class="mobile-hide mobile-container">
              <p>Some text..</p>
          </div>

          <button onclick="accordion('event')"
             class="mobile-button mobile-block mobile-theme-l1
             mobile-left-align">
             <i class="fa fa-calendar-check-0 fa-fw
             mobile-margin-right"> My Events</i>
          </button>

          <div id="event" class="mobile-hide mobile-container">
              <p>Some other text..</p>
          <div>

          <span class="hljs-string"><button onclick="accordion('photo')"
                class="mobile-button mobile-block mobile-theme-l1
                mobile-left-align"><i class="fa fa-user
                fa-fw mobile-margin-right"> My Photos</i>
          </button>

          <div id="photo" class="mobile-hide mobile-container">
            <div class="mobile-row-padding">
               <br>

               <div class="mobile-half">
                  <img src="./image/paul_tuon.jpg" style="width: 100%"
                  class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="./image/paul_tuon_graduation.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="./image/paul_tuon.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="./image/paul_tuon_graduation.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="image/paul_tuon.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>

               <div class="mobile-half">
                  <img src="image/paul_tuon_graduation.jpg"
                  style="width: 100%" class="mobile-margin-bottom">
               </div>
            </div>  <!-- end div class="mobile-row-padding" -->
          </div>  <!-- end div id="photo" -->
        </div>  <!-- end div class="mobile-pale-blue" -->
      </div>  <!-- end div class="mobile-card mobile-round" -->

   <!-- end accordion style feature! -->

</div> <!-- end middle column -->

<!-- start right column -->

<!-- here it is: right column is 2/12 of the grid -->

<div class="w3-col m2">
   <div class="w3-card w3-round w3-aqua w3-center">
      <div class="w3-container">
         <p>Upcoming Events:</p>

         <img src="./image/image_105.jpg" class="w3-margin-bottom"
                 style="width:100%">

         <p><strong>Holiday</strong></p>
         <p>Friday 15:00</p>
         <p><button type="button" class="w3-button w3-theme-14
            w3-block">Info</button></p>
      </div>
    </div>

    <div class="w3-card w3-round w3-pink w3-center">
      <iv class="w3-container">
         <p>Friend Request</p>
         <!--
         <img src="./image/graduation.jpg" class="w3-margin-bottom"
                 style="width:50%">
         -->
         <span>Jane Doe</span>
         <div class="w3-row w3-opacity">

           <div class="w3-half">
              <button type="button" class="w3-button w3-block-14
              w3-green w3-section" title="Accept">
              <i class="fa fa-check"></i></button>
           </div>

           <div class="w3-half">
              <button type="button" class="w3-button w3-block-14
              w3-red w3-section" title="Decline">
              <i class="fa fa-remove"></i></button>
           </div>
         </div>
       </div>
    </div>
    <br>

    <div class="w3-card w3-round w3-purple w3-padding w3-center">
       <p>ADS</p>
    </div>
    <br>
</div> <!-- end right column -->

<!-- here is the closing div for class w3-row! -->

</div> <!-- end grid containing class w3-row -->

<!-- here is the closing div that contains class w3-container! -->

</div> <!-- end page container -->


<!-- here is the last section of the website: footer -->

<!-- start footer -->

<footer class="w3-container w3-theme-d3 w3-padding-16">
   <div>Follow us on social medias: Facebook, Twitter, Instagram!</div>
   <div class="w3-right">Contact: john@doe.com</div>
</footer>


<script>
// Accordion
function myFunction(id)
    {
     var x = document.getElementById(id);
     if (x.className.indexOf("w3-show") == -1)
        {
         x.className += " w3-show";
         x.previousElementSibling.className += " w3-theme-d1";
        }
     else
        {
         x.className = x.className.replace("w3-show", "");
         x.previousElementSibling.className =
         x.previousElementSibling.className.replace(" w3-theme-d1", "");
        }
    }


// used to toggle on smaller screen when clicking on the menu button
function openNav()
    {
     var x = document.getElementById("navDemo");
     if (x.className.indexOf("w3-show") == -1)
        {
         x.className += " w3-show";
        }
     else
        {
         x.className = x.className.replace(" w3-show", "");
        }
    }
</script>

</body>
</html>


/* there you have it! */
/* a responsive mobile image slider */
/* when the website is loaded using a mobile */
/* device the slider showing one image sliding */
/* at a time! */

/* again, check out the plugin website mentioned earlier */
/* to find all kinds of plugins to use on your website! */
b
/* go at it! */

Incorporate Fontawesome in a Website for Beginners

Fontawesome is a collection of ready-made images available to anyone for free. For a visual view on some examples of fontawesome images, go to my other website called "MondayThruSunday.COM," and look in all of the menu items and there should be a fontawesome in the front of the menu name for each menu item.

For example, for a menu name called "Home," there is a fontawesome image looking like a house in the front of the word "Home"; for a menu name called "Search," there is a fontawesome image looking like a magnifying glass in the front of the word "Search"; for a menu name called "Signup," there is a fontawesome image looking like three horizontal hash bars in the front of the word "Signup."

Fontawesomes are easy to use and most of all, you don't need to download them from somewhere and install them on your computer. They are available via the browser technology and the HTML.

To use fontawesomes, all you have to do is include the link to a CDN and then referring to its name as a class name inside your HTML element document -- the same way you refer to your CSS class names. See an illustration below.

Fontawesome images class starts with the word "fa fa-." For examples:

In the head <head> section of your HTML file, include the below link:

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

Again, a CDN (or Content Delivery Network) is just a central data

network that mainly delivering data content to users via a link!

Note that there are hundreds of CDNs out there that you can link to.
The above link is just one of those. Google has one and so does Bootstrap.
Here is a CDN from Bootstrap:

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

So it is just a matter of preference of which CDN to use and all will work just fine!

After you included the link, you can refer to the font awesome images as
you normally would the same way you refer to a CSS class. For example:

In the body <body> section of your HTML file, do this:

<div class="fa fa-home"></div>      will display an image of a house: 
<div class="fa fa-home"> Home</div> will display:
Home
<div class="fa fa-bars"></div> will display an image of three horizontal hash bars:
<div class="fa fa-search"></div> will display an image of a magnifying glass: <div class="fa fa-check"></div> will display an image of a checkmark:
<div class="fa fa-globe"></div> will display an image of a globe:
<div class="fa fa-cart-arrow-down"></div> will display an image of a shopping cart:
<div class="fa fa-plus"></div> will display an image of a plus sign:

There are thousands of fontawesome images available on the Internet for free to use. Just Google the term "fontawesome" and it will give a lot of results to choose from.

Earlier, I mentioned that you don't need to download fontawesome images anywhere from the Internet. That is true for the standard fontawesome images that are provided by the World Wide Web consortium.

However, for thousands of specialized third party fontawesome images like specialized shopping cart [where you can customize the inter-activity of the cart] and others, you need to download them from the Internet and store them in your folders and refer to them accordingly.

All CDNs do the same thing: they gather all of the fontawesome images and store them in a directory on their server and provide a link to the public to link to.

For more about fontawesome tutorials, please check out this site: https://www.w3schools.com/css/css_icons.asp

Here is another excellent fontawesome tutorial: https://www.w3resource.com/icon/font-awesome/web-application-icons/cart-arrow-down.php

Here is the official site of the standard fontawesome consortium site: https://fontawesome.com/icons/cart-arrow-down

Here is the official site of the standard fontawesome consortium site that lists a fontawesome cheat sheet that you can basically find a particular fontawesome image quickly: https://fontawesome.com/cheatsheet?from=io

Advancing Your Programming Skills: CSS Badge

Here is an interesting topic that you might find very useful: CSS Badge

/** showing the number of items in the cart **/

/** here, assuming you have a shopping cart that has a **/
/** variable called $cart_count that holds the number of  **/
/** items in the cart **/

cart<a href="#"><span class="badge" id="cart-count"><?=$cart_count?></span></a>

For more tutorial on "badge" please click on the link below!

CSS Badge

Advancing Your Programming Skills

As mentioned earlier multiple times, the best place to advance your programming skills is the W3Schools. One of the many topics that you might want to spend some time on learning is the "dialog modal" box tutorial that can be found here: https://www.w3schools.com/bootstrap/bootstrap_modal.asp. With the modal dialog box, you can put all kinds of content to make your users interact with it.

Here are some of the interesting topics that you might want to spend some time learning:

https://www.w3schools.com/bootstrap/bootstrap_carousel.asp https://www.w3schools.com/bootstrap/bootstrap_affix.asp https://www.w3schools.com/bootstrap/bootstrap_glyphicons.asp https://www.w3schools.com/bootstrap/bootstrap_pagination.asp https://www.w3schools.com/bootstrap/bootstrap_images.asp https://www.w3schools.com/css/css_image_gallery.asp https://www.w3schools.com/css/css3_text_effects.asp https://www.w3schools.com/html/html_entities.asp

So there are lots of topics available for you to improve your programming skills. So go at it!!!

Simple Tricks

When you program websites, you might run into situations that require you to be creative instead of using CSS to accomplish your tasks. One of the neat trick is to use non-breaking space command or &nbsp; to put some spaces between your content, as the "<marquee></marquee>" example below shows.

One &nbsp; is approximately equals to 10 pixels. As you can see in the example below, it requires a lot of &nbsp; to make the spaces wide enough.

The drawback of using &nbsp; instead of CSS is that it is very cluttered and messy; however, it is much quicker and easier than having to write CSS definitions.

Sometimes you can't write CSS definitions to fit your goal as in my case below. So you are left to use &nbsp; to accomplish the task.

Nonetheless, be very careful using &nbsp; instead of CSS because in mobile devices it might not display very well, especially if you have lots of &nbsp;.

So use it sparingly is the best way to use it. Don't over-use it!

In my case, it works very well on any mobile devices.

So there you have it! A very neat trick to use!!!

A Bonus: A Simple Trick to Scroll Contents

Here is a very simple trick to make your website looks awesome.

You won't see this trick anywhere in the document or tutorials
anywhere but only right here from me.

I use this trick on my own websites on a regular basis.

Here it is:

<div style="width: 700px; height: auto; background-color: #ffdddd;
            padding: 5px 5px 5px 5px"><marquee>Content to scroll!</marquee>
</div>

The tag is called "<marquee></marquee>"

This simple tag scrolls continuously any content you put in it!

You can put this "<marquee></marquee>" tag anywhere as a
standalone or inside any HTML elements: <div>, <span>, <p>, etc.

You can also style your <marquee> content, such as
configuring the width and height and background color, etc.

Here is the same code that I use on my website: ZeroNilZilch.COM.

Notice that I embedded the styling code directly in the <marquee></marquee> as
appose to putting it in the <div></div> or other HTML elements.

It is just a personal preference and any HTML elements will work just fine.

As you can see, I had to use lots of &nbsp; to make enough spaces between contents!

The listing of &nbsp; between contents is a continuous line, but here,
it is broken down into multiple lines for displaying purpose!

<marquee bgcolor="white" width="100%" height="50">
   <font size="5" color="#00FF99">www.ZeroNilZilch.COM</font>&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#3333FF">Where the future is already here!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#00FFFF">Explore, see the horizon,
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   open your mind and let your curiosity run wild,
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   discover, inspire and enrich your learning!!!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#3333FF">The engine of your inginuity is limited only to
                                  your imagination!!!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#FF66FF">
   Welcome to the 21st century and beyond where digital mobile rules!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#1883FF">
   This website and all of our affiliate sites are mobile-friendly!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#00FFFF">
   This means that you can use your mobile phones or any portable
   small device to surf and shop with us conveniently and securely at all of our
   affiliate sites!!!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#FF66FF">They're built for the Millenials,
   where all things Millenial, the Millenials' way!!</font>
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <font size="5" color="#3333FF">Go ahead and fire up your smartphones and load
   this website and see if it's mobile-friendly or not!</font>
</marquee>

A Simple Trick to Display Text Vertically

Here is a very simple trick to make your texts appear vertically as well as other text effects that you might find useful. Please check these out:

https://www.w3schools.com/cssref/css3_pr_writing-mode.asp https://www.w3schools.com/css/css_align.asp https://www.w3schools.com/cssref/pr_text_text-decoration.asp https://www.w3schools.com/cssref/css3_pr_transform.asp https://www.w3schools.com/cssref/css3_pr_transition.asp https://www.w3schools.com/cssref/tryit.asp?filename=trycss_zindex

A Simple Trick to Display Navigation Bar Using HTML NAV Tag

Here is a very simple trick to make your navigation bar works on mobile devices. On desktop it will display the menu items horizontally but on mobile devices, it will display them vertically.

Note that on mobile devices, the menu bar will be cleared all of menu items and a fontawesome fa fa-bars: is used instead in place of the menu items and the fa fa-bars is shown on the menu bar as a button to click.

When a user clicks on the fa fa-bars symbol it opens up the menu items listing the menu items vertically and neatly.

Using NAV tag, you don't need to do any special tricks to make it mobile-friendly: it is already built-in the browser technology.

Just list your menu items to make it work on desktop devices as you normally would and the browser technology takes care of the mobile devices display behind the scene for you so that you don't need to do any special tricks:

https://www.w3schools.com/tags/tag_nav.asp

There you have it! A secret way to beautify your website!!!

A Simple Trick to a Mobile-friendly Website

Here is a very simple trick to make your website mobile-friendly. First of all, this is just a simple trick that is suited to some small situations where CSS is too complicated and too bulky to use. This trick works very well when you have a section of the code needs to handle small mobile devices and another section next to it can be used for desktop devices. For example:

<?php
/** this is a special trick that you'll never see from **/
/** any documentation or tutorials anywhere, period! **/

/** here is the special trick using a combination of PHP and Javascript: **/

echo "<script language='javascript'>

/** you need a space between the echo " and location **/

echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
      . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
echo "</script>\n";

/** basically, the code above picks out the width and height **/
/** of the device using Javascript screen object and just **/
/** referring to the object's property: width and height! **/
/** very neat and simple! **/

/** the reference to 'location.href' is just reading the url's **/
/** incoming request and picking off the querystring at **/
/** the same time! **/

/** okay, let's see how it works! **/

/** first, you test the size of the device **/

/** in other words, when the browser hits this code above, **/
/** it checks to see what size the device is. **/

/** if it is a desktop device being used to surf this website, **/
/** it will execute the area of the code designed to be used on desktop! **/

/** if it is a mobile device being used to surf this website, **/
/** it will execute the area of the code designed to be used on mobile **/
/** devices **/

/** this is much simpler than having to write CSS definitions **/
/** it works just as good as if you had written a CSS definition to **/
/** do the job! **/

/** as a matter of fact, the groups that wrote the CSS rules to **/
/** make CSS definitions mobile-friendly used this same technique to **/
/** detect the devices to make their CSS rule do the job **/
/** of detecting the various mobile size! **/

/** they called it media definition that looks like this: **/

@media (max-width: 480px)
     {
      .nav-collapse
           {
            -webkit-transform: translate3d(0, 0, 0);
           }
      .page-header h1 small
           {
            display: block;
            line-height: 20px;
           }
     }

/** but first, you need to test if the browser can read **/
/** the dimensions of the device being used to surf the webpage! **/

/** all browsers returns a width and height of the device being **/
/** used every time it loads the webpage! **/

/** but we need to use a special trick that you'll never see from **/
/** any documentation or tutorials anywhere, period! **/

/** here is a special trick using a combination of PHP and Javascript: **/

<?php
if (isset($_GET['width']) AND isset($_GET['height']))
   {
    global $width;
    global $height;
    // grab the geometry variables
    $width  = $_GET['width'];
    $height = $_GET['height'];
    if ($width > 600)
       {
        // desktop device! prepare code to be used on desktop!
?>
        <!-- left column -->
        <div class="mobile-col m3">

            <!-- display left column content for desktop! -->

        </div>
        <!-- end left column -->

        <!-- middle column -->
        <div class="mobile-col m7">

            <!-- display middle column content for desktop! -->

        </div>
        <!-- end middle column -->

        <!-- right column -->
        <div class="mobile-col m2">

            <!-- display right column content for desktop! -->

        </div>
        <!-- end right column -->
<?php
       } // end if $width > 600
    else
       {
        // mobile devices! prepare code to be used on mobile devices!

        // notice that inside this mobile section, you still need to
        // use CSS to style the content to be mobile-friendly!

        // I told you earlier that this simple trick doesn't do all of
        // your mobile-friendly works! it does for certain situations only!
        // you can use both this trick and CSS definitions to your advantage!
?>
        <!-- left column -->
        <div class="mobile-col m3">

            <!-- display left column content for desktop! -->

        </div>
        <!-- end left column -->

        <!-- middle column -->
        <div class="mobile-col m7">

            <!-- display middle column content for desktop! -->

        </div>
        <!-- end middle column -->

        <!-- right column -->
        <div class="mobile-col m2">

            <!-- display right column content for desktop! -->

        </div>
        <!-- end right column -->
<?php
       } // end else if $width > 600
   } // end if (isset($_GET['width']) AND isset($_GET['height']))
else
   {
    // pass the geometry variables (preserve the original query string
    echo "<script language='javascript'>\n";
    echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
           . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
    echo "</script>\n";

    // if for some reasons that the browser fails to grab the dimensions
    // it will come here and you can handle that case accordingly!

    // that situation is very rare! this code above always returns
    // the dimensions!

    // desktop device! prepare code to be used on desktop!
?>
        <!-- left column -->
        <div class="mobile-col m3">

            <!-- display left column content for desktop! -->

        </div>
        <!-- end left column --<

        <!-- middle column -->
        <div class="mobile-col m7">

            <!-- display middle column content for desktop! -->

        </div>
        <!-- end middle column -->

        <!-- right column -->
        <div class="mobile-col m2">

            <!-- display right column content for desktop! -->

        </div>
        <!-- end right column -->
<?php
   }
?>

There you have it! A secret way to beautify your website by making it mobile-friendly!!!

Analytics Tools For Tracking Your Visitors

Here is an interesting topic that you might find very useful: Tracking Visitors of Your Website

You can write your own simple cookies code to capture your website visitors or use the professionally-made tools and here are a few to choose from.

If you want to write your own simple cookies code to capture your website visitors, check the following out:

Create A Simple PageView Counter Using PHP and MySQL

Seriously? Really? The code above was being written in the year 2020? Am I seeing it right?

The old MySQL API was deprecated in the year 2015 and the code above was being written in the year 2020?

Amazingly, even the code was being written in May 2020 and the author still uses the old MySQL API that has been deprecated a long time ago and it has no longer in used ever since.

Anyhow, to correct the problem, you need to rewrite the connection code in PDO. For a brief tutorial, see my other tutorial called "Introduction to PDO."

Here is a partial code found in the tutorial listed above that needs to be rewritten:

// the author is using a localhost for building and testing
// so you need to replace the db connection values accordingly
// when migrating to a "live" web hosting

$host = "localhost";
$username = "root";
$password = "";
$databasename = "sample";

$connect = mysql_connect($host, $username, $password);
$db = mysql_select_db($databasename);

// change the two lines above to the following:

$connect = new PDO(mysql:host=$host;dbname=$databasename",
                               $username, $password);

So look for a code fragment that says:

$check_ip = mysql_query("select userip from pageview
where page='yourpage' and userip='$user_ip'");

if (mysql_num_rows($check_ip)>=1)
   {
	
   }
else
   {
    $insertview = mysql_query("insert into pageview
    values('','yourpage','$user_ip')");
	$updateview = mysql_query("update totalview
    set totalvisit = totalvisit+1 where page='yourpage' ");
   }

Modify the above code to look like the following:

try
    {
     $sql = $connect->prepare("SELECT userip FROM pageview
            WHERE page = ':yourpage' AND userip = ':user_ip'");

     $check_ip = $sql->execute(array($yourpage, $user_ip));
    }
catch (PDOException $e)
    {
     echo 'ERROR: Cannot retrieve data. ' . $e->getMessage();
    }

if ($check_ip)
   {
    // found view counts and do nothing!
   }
else
   {
    // try to insert another visitor/pageview to the database
    try
        {
         $sql = $connect->prepare("INSERT INTO pageview
                          VALUES (?, ?)");

         $insertview = $sql->execute(array('page' => $yourpage,
                                           'userip' => $user_ip));
        }
    catch (PDOException $e)
        {
         echo 'ERROR: Cannot insert data. ' . $e->getMessage();
        }

    // also try to update visitor/pageview
    try
        {
         $totalvisit++;

         $sql = $connect->prepare("UPDATE totalview
                SET totalvisit = ? WHERE page = ? ");

         $updateview = $sql->execute(array($totalvisit, $yourpage));
        }
    catch (PDOException $e)
        {
         echo 'ERROR: Cannot update data. ' . $e->getMessage();
        }

// Change the following code accordingly:

<body>
  <?php
    // Use a SELECT query similar to the one shown above!

    $stmt = mysql_query("select totalvisit from totalview where page='yourpage' ");

    // The one line below can be replaced by the result from the SELECT query above!
    // Just put: echo $stmt . 'times.'
  ?>

  <p>This page is viewed <?php echo mysql_num_rows($stmt);?> times.</p>
</body>

The tutorial above mentioned a variable called $yourpage, which the author didn't explain how to get it. Here is how you assign value to variable $yourpage:

// take all of the following code beginning with the $protocol line and all the
// way to the end at the "$yourpage" line and place them at the top of the
// code example above right before the line that says: $host = "localhost";

// protocol = http or https
$protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === 0 ? 'https://' : 'http://';

// so instead of the above shortcut/simpler protocol code, you can use this much
// more robust and complete protocol code (by uncommenting the following three lines):

// $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||
//             $_SERVER['SERVER_PORT'] == 443 ||
//             $_SERVER['HTTP_X_FORWARDED_PORT'] == 443) ? "https://" : "http://"

// if you uncomment the three lines above, remove the below port statement completely
// and also take out the variable $port in the $yourpage line (below) as well!

// or if you use the shortcut/simpler protocol code above, you can take out the
// variable $port below as well and it will work just fine!

// in both cases, including port is just not necessary as the computer already
// knows what port it is running on.

// so omitting port entirely will work just fine!

// for beginners, I suggest that you omit the port option to avoid specifying the
// wrong port and perhaps causing problems!

$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":" . $_SERVER["SERVER_PORT"]);

$yourpage = $protocol .
            $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];

As you can see, now $yourpage contains your actual page. Put the whole code in every page that you want to track. When a visitor visits a page that contains the (whole) code it will execute the whole code and therefore captures visitor's information and saves visitor's information in the database.

As you may well aware, the author of the tutorial above didn't do a good job explaining and didn't even finish the tutorial. It's a complete disaster! I'm not about to finish someone else's tutorial, and, therefore, leaving it to you to judge on your own and maybe finish the job yourself. Good luck!

The next one is much better! Try it!

PHP Program to count Page Views

Build a Visitor Tracking System for your Website with PHP

How To Track Visitor IP, Visited Page, Visiting Time Using PHP

What is the best way to track visitors?

Track visitors PHP Tutorial

If you use the last list code example above from GeekLabel.COM, there is a minor typo in the code and it won't work as intended. So look for a code fragment that says:

else if (!isset($HTTP_USER_AGENT))
   { 
    $HTTP_USER_AGENT = ''; 
   }

Remove the else clause so that it reads:

if (!isset($HTTP_USER_AGENT))
   { 
    $HTTP_USER_AGENT = ''; 
   }

Now the code should work as intended.

The code above uses the old MySQL API that is deprecated and no longer in used. You need to rewrite the connection code in PDO. For a brief tutorial, see my other tutorial called "Introduction to PDO."

Here is a partial code that needs to be rewritten:

// you need to replace the db connection values accordingly

$hostname_visitors = "host";
$database_visitors = "database";
$username_visitors = "username";
$password_visitors = "password";

$visitors = new PDO(mysql:host=$hostname_visitors;dbname=$database_visitors",
                               $username_visitors, $password_visitors);

So look for a code fragment that says:

//write the required data to database
mysql_select_db($database_visitors, $visitors);
$sql = "INSERT INTO visitors_table (visitor_ip, visitor_browser, visitor_hour,
       visitor_minute, visitor_date, visitor_day, visitor_month, visitor_year, 
       visitor_refferer, visitor_page) VALUES ('$visitor_ip', '$visitor_browser', 
       '$visitor_hour', '$visitor_minute', '$visitor_date', '$visitor_day',
       '$visitor_month', 
       '$visitor_year', '$visitor_refferer', '$visitor_page')";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);

Modify the code so that it reads:

//write the required data to database
$sql = $visitors->prepare("INSERT INTO visitors_table (visitor_ip, visitor_browser,
       visitor_hour, visitor_minute, visitor_date, visitor_day, visitor_month,
       visitor_year, visitor_refferer, visitor_page)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$result = $sql->execute(array('visitor_ip' => $visitor_ip,
          'visitor_browser' => $visitor_browser, 
          'visitor_hour' => $visitor_hour',  // Typo: remove the ' at the end
          'visitor_minute' => $visitor_minute',  // Typo: remove the ' at the end
          'visitor_date' => $visitor_date', 'visitor_day' => $visitor_day',
          'visitor_month' => $visitor_month',
          'visitor_year' => $visitor_year',
          'visitor_refferer' => $visitor_refferer',
          'visitor_page' => $visited_page')); // Typo: $visited_page and NOT $visitor_page
if (!$result)
   {
    echo 'Cannot insert data into database.';
   }

Look for the next code fragments that say: $additionalQuery = "SQL_CALC_FOUND_ROWS " and mysql_select_db($database_visitors, $visitors) and remove them both entirely.

Of course, you need to modify the rest of the old MySQL code accordingly, including this fragment: $query_visitors = "(SELECT ".$additionalQuery." * FROM visitors_table WHERE" to SELECT count(*) FROM visitors_table WHERE".

Pay special attention to the function called selfURL() because it returns the page of your website that the visitors visited. You would want to know exactly what page your visitors visited on your website and this function gives you that information. There is a typo that says: 'visitor_page' => $visitor_page' and it should be corrected to 'visitor_page' => $visited_page.

There are also lots of typos that says: 'visitor_page' => $visitor_page' and the oppostrophe at the end should be removed to be 'visitor_page' => $visited_page.

If you want to use the professionally-made tools and here are a few to choose from:

Paid Web Analytics Tools For Tracking Your Visitors

Web Analytics Tools For Tracking Your Visitors

10 Web Analytics Tools For Tracking Your Visitors

My Code to Track Visitors

Here is my "barebone" simple code to track your visitors visiting on the index.php front page of your website. Any time a visitor visits your website, which is primarily being visited on the index.php front page, it tracks that person as one visit. If that person returns to visit your website again on another occassion on another session, it accounts for that visit as another one visit as well.

In other words, it logs each visit by a person as one visit no matter how many pages or area a visitor is visiting because this "barebone" simple code is designed to track only one page, which is the index.php front page. When a person continues to visit other pages on your website it does not account for those visits.

When a person leaves the website entirely and comes back to visit the website again, it again will log that person as one unique visit without differentiating the visit as a return visit. It keeps doing this for all other visitors as well.

It tallies all of the visits from all visitors [new or old visitors] that enter the website on every session to account for the website traffic. The total count of the page hits does not account for the return visits by the same person.

You can make improvement to this code as well or use it "AS IS" without any modification.

First of all, you will need to create a MySQL database to store all of your page hits.

To track your website traffic, just put all of the below code in a PHP file (perhaps, name it as pagehit.php) and then include this file name (pagehit.php) at the top of your index.php front page. See an example index.php front page later.

Remember that the following code is written to log only one page, which is assumed to be an index.php front page. So put the whole code below at the top of your index.php front page.

However, you can track page hits on every page of your website as well -- not just the index.php front page.

To count page hits on all of your website pages, just include this file name (pagehit.php) in every one of your pages. It will log different querystrings for different pages.

So the key thing to come away with this code (below) is that you can place the below code at the top of every page of your website if you want to track each page. However, it will distort your total page hits because a visitor may visits all of your pages and since each of your page contains a code to capture the page hit, the total page hit will be larger than it should be.

Let's put it this way: You want to track your website's unique traffic but if a visitor visits all of your pages or just some of your pages, the page hits will not reflect the true website's unique traffic. That's why this code below was designed to track only the index.php front page so that it accurately tracks the website's unique traffic.

So if you put the below code at the top of every page on your website it will just add all of the page hits together from all of your pages, including the index.php front page. In other words, it combines all of the page hits from all of your pages as one total and this total does not reflect the true unique traffic of the site.

So if you want to know which page got how many hits, you'll have to modify the code slightly because the code below just lump all of the various page hits together as one total, and this total includes the hits on the index.php front page, too.

Notice that you can either put the following code in a PHP file (pagehit.php) and include it like [include("pagehit.php")] in every page of your website OR just copy and paste the entire code and put it at the top of every page of your website and it will work just fine.

File: pagehit.php
<?php
/**
 * a function to count how many times visitors visit a particular page
 *
 * you can call this function by passing a page file to it
 *
 * see at the bottom of this function to see how it is being called
 *
 * notice that argument $page can be any page on your website, but
 * the database code just add all of the page hits together regardless
 * of what page or pages you pass to it!
 *
 * this is where you can modify the database code slightly to store
 * the different page hits individually! it's up to you to modify it!
 *
 * if you don't really care which page gets the most hit and only
 * care about the whole website's total hit, then there is no need to
 * modify this code! just use it "AS IS" and include the file
 * pagehit.php at the top of the index.php front page and don't
 * include this file in any of your pages because the index.php file
 * is the only file we're tracking! nothing else!
 */

public function pageCounter($page, $referer)
     {
      // you might want to pass these connection parameters
      // from external source instead of embedding them like here!

      $hostingserver = 'root';
      $databaseName = 'your_database_name';
      $username = ''; // your database username
      $password = ''; // your database password

      // try to create a PDO connection instance
      try
          {
           $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName",
                                             $username, $password);
           $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          }
      catch (PDOException $e)
          {
           echo 'Cannot connect to the PDO database. ' . $e->getMessage();
          }

      // now try to create a table named pagecounter if it
      // doesn't already exist in the database

      // if it already exists in the database, it will skip this try/catch blocks!

      // in other words, it won't create a table named `pagecounter` because
      // it already exists in the database!

      // however, it will continue executing all codes following the try/catch
      // blocks!

      // FYI:

      // I've found that for some shared hosting's PDO engine doesn't
      // recorgnize this statement:

      // 'CREATE TABLE IF NOT EXISTS'

      // to solve that problem, remove the below statement and create the table
      // manually using PHPmyAdmin or some other means!

      // so you don't actually need to test this condition (below) every time a
      // page is hit! in other words, you don't need to check if the table
      // exists or not, because you already know that a table already have been
      // created, and, therefore, there is no need to use the condition
      // code below!

      // just remove the create table condition below and make sure your table
      // have been created already and it will work just fine!

      try
          {
           $sql = $conn->prepare("CREATE TABLE IF NOT EXISTS `pagecounter`
                                    (
                                     `id` int(25) NOT NULL auto_increment,
                                     `page_name` varchar(255) NOT NULL default '',
                                     `referer` varchar(255) NULL default '',
                                     `page_hit` int(25) NOT NULL default '0',
                                     `date_time` datetime NOT NULL default
                                     CURRENT_TIMESTAMP,
                                     PRIMARY KEY  (`id`)
                                    ) TYPE=MyISAM"
                                );

           // execute the query to create the table
           $sql->execute();
          }
      catch (PDOException $e)
          {
           echo 'Cannot create table pagecounter. ' . $e->getMessage();
          }

      // after creating the table, it's time to insert new page hits

      // but first, check to see if there are any page hits already stored
      // in the database

      $query  = $conn->prepare("SELECT * FROM pagecounter
                                         WHERE page_name = :page");

      $result = $query->execute(['page' => $page]);

      // check to see if there are any page hits already stored
      // in the database

      if ($result)
         {
          // yes, there are page hits already stored in the
          // database!

          $result->setFetchMode(PDO::FETCH_ASSOC);

          while ($row = $result->fetch())
              {
               // so just add the new page hit to the total

               $counter = $row['page_hit'] + 1;
              }

          // after adding a new page hit to the total,
          // we need to update the total page hits and as well as
          // updating the rest of the record, too!

          $update  = $conn->prepare("UPDATE pagecounter
                                        SET page_name = :page,
                                            referer = :referer,
                                            page_hit = :counter");

          $update->execute([':page' => $page,
                            ':referer' => $referer,
                            ':counter' => $counter
                           ]
                          );
         }
      else
         {
          // this must be for the first page hit!

          // there are no page hit stored in the database,
          // so we need to store the first page hit in the database

          $stmt = $conn->prepare("INSERT INTO pagecounter
                                  VALUES (?, ?, ?)"
                                );

          $stmt->execute([
                           'page_name' => $page,
                           'referer' => $referer,

                           // since there are no page hits stored in the
                           // database, so it must be the first time,
                           // and therefore, 'page_hit' is set to 1

                           'page_hit' => '1'
                          ]
                         );

          // if you observe the create table code definition
          // and the insert table code above, you'll notice that
          // there are 5 table fields in the create table code
          // while only 3 fields (page_name, referer, and page_hit) are
          // performed in the insert/update table code above.

          // if you look closely in the create table definition
          // you'll notice that the 'id' field contains the
          // "auto_increment" clause that MySQL uses to increment
          // this 'id' automatically starting with number 1 and
          // increments it by 1 each time you insert a row of record.

          // therefore, the 'id' field is not directly handled by
          // programmers -- it is handled by MySQL automatically.

          // likewise, the `date_time` field is not directly handled by
          // programmers, either -- it is handled by MySQL automatically,
          // because it was declared in the definition to use a
          // 'default' date time value, generating a date and time
          // automatically every time an insert or an update operation
          // is taking place.

          // the function CURRENT_TIMESTAMP generates the date and time
          // automatically!

          // so it looks like this:

          // `date_time` datetime NOT NULL default CURRENT_TIMESTAMP


          // self-explanatory!


          // now on to the code flow:

          // since this is the first time a visitor saw this
          // page, we initialize the page to one hit!

          // the next time any visitor visits this page it
          // will not come here in the "else" condition because
          // $result contains some value(s) for the tracking page!

          $counter = 1;
         }

      // return the result of the query back to the caller!
      // this is the number of times the page has been hit by visitors!

      return $counter;
     } // end function pageCounter($page, $referer)

/**
 * now that the function has been written, we can call that function
 * from anywhere!
 *
 * to call that function, you have to include the following snippet
 * of code!
 *
 * put the following code at the top of every page you want to track!
 */

// HTTP headers

// every time the Web runs it fires off the HTTP protocol and PHP has a
// a built-in variable called $_SERVER to grab all of the HTTP headers.

// The superglobal array variable $_SERVER has 32 values, i.e.,

// $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_REFERER'], $_SERVER['SERVER_NAME'],
// $_SERVER['QUERY_STRING'], $_SERVER['SCRIPT_NAME'], $_SERVER['PHP_SELF'],
// $_SERVER['IP_ADDRESS'], $_SERVER['DNT'], etc.

// and you can view these values by running in your view (index.php)
// page or in any page output code like this:

// print_r($_SERVER);

// here, we grab the page's url using the HTTP protocol,
// particularly the built-in (superglobal) array variable $_SERVER.

// in here, we're just grabbing those HTTP headers, such as the URI or URL,
// including the querystrings. that's what the following code is doing!

// the $_SERVER['PHP_SELF'] code is to refer to the current file itself!
// so if you put $_SERVER['PHP_SELF'] inside a file called index.php, it
// will run that file!

// as for $_SERVER['SERVER_NAME'] is to grab the server name, i.e.,
// example.com.

// as for $_SERVER['HTTP_REFERER'] is to grab the url that the visitor
// just came from!

// for example, if a visitor came to your website from another website
// called http://www.example.com, $_SERVER['HTTP_REFERER'] returns
// http://www.example.com

// as for $_SERVER['QUERY_STRING'] is to grab the url's querystring, the
// string after the '?', i.e.,
// www.example.com/?arg1=value1&arg2=value2&arg3=value3

// so this will look something like these:

// www.example.com/index.php?arg1=value1&arg2=value2&arg3=value3
// www.example.com/catalog.php?arg1=value1&arg2=value2&arg3=value3
// www.example.com/affiliate.php?arg1=value1&arg2=value2&arg3=value3
// www.example.com/mypage.php?arg1=value1&arg2=value2&arg3=value3

/**
 * here are some useful items you might find useful:
 *
 * $visitor_hour = date("h");
 * $visitor_minute = date("i");
 * $visitor_day = date("d");
 * $visitor_month = date("m");
 * $visitor_year = date("y");
 */

$self_url = $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . '?' .
            $_SERVER['QUERY_STRING'];

// grab the url of the visitor's last link!

$referer = $_SERVER['HTTP_REFERER'];

// we call pageCounter() and getting a page hit instantly
$page_hit = pageCounter($self_url, $referer);

/**
 * now that we have a page hit we can do whatever we want, such as
 * display it somewhere on the same page. how you use this page hit
 * is up to you, but here we just echoing out to the browser to
 * display the page hit on the same page!
 */

echo $page_hit;

/**
 * what if you want to put the display of the page hit somewhere
 * on your website beside the default front index.php page?
 *
 * in other words, you want to put a hit counter in a different page
 * other than the front index.php.
 *
 * in that case, you have to query the database using the code
 * similar to the following. see a seperate index.php example below.
 *
 * you need to put this code at the very top of your xxx.php page!
 *
 * // try to create a PDO connection instance
 * try
 *     {
 *      $conn = new PDO("mysql:host=$hostingserver;dbname=$databaseName",
 *                                            $username, $password);
 *      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 *     }
 * catch (PDOException $e)
 *     {
 *      echo 'Cannot connect to the PDO database. ' . $e->getMessage();
 *     }
 *
 * $query  = $conn->prepare("SELECT * FROM pagecounter
 *                                    WHERE page_name = :page");
 *
 * $result = $query->execute('page' => $page);
 *
 * if ($result)
 *    {
 *     $result->setFetchMode(PDO::FETCH_ASSOC);
 *     while ($row = $result->fetch())
 *         {
 *          $counter = $row['page_hit'] + 1;
 *         }
 *    }
 *
 * and then you can basically display the hit page anywhere on
 * your xxx.php. for example:
 *
 * <p>Total visits: <?=$counter?>
 *
 * see the "barebone" index.php page below as an example!
 */
?>

The example above can be used to display in the "barebone" index.php front page as well.

Here is a "barebone" index.php front page example to show how to include the pagehit.php file at the top of your index.php front page.

File: index.php
?<php
// here, assuming you name the whole code above as pagehit.php

// this is it! just one line!

// very simple to include a tracking script on
// your index.php front page!

// don't forget to put the file pagehit.php at the same level
// in directory as your index.php

include(pagehit.php);
?>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>My Home Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="language" content="en" >
<link href="./asset/44ab1983/css/style.css" rel="stylesheet">
<script src="./asset/16eb9947/jquery.js"></script>
<style>
html,
body
    {
     width: 100%;
     height: 100%;
     background-color: #e6e6ff;
    }

#product-item
    {
     background-color: white;
     padding-left: 10px;
     padding-right: 10px;
    }
</style>

<script type="text/javascript">
$(document).ready(function()
    {
     public function example(arg)
          {
           // function code
          }
    });
</script>

</head>

<body>
     <div>
         content of the div
     </div>

     <div>
       <table>
         <tr>
           <td>
             td content
           </td>
         </tr>
       </table>
     </div>

     <div>
       content of the div
       <a href="#">link</a>
     </div>
</body>
</html>

There you have it! An easy way to track your website's visitors!!!

Migrating Your Website to a Real "Live" Server

Now that you've got your website with all the bells and whistles, you can migrate it to your live server to make your website live online for your visitors all over the world to see.

There are plenty of web hosting providers out there: both for paid hosting and for free hosting. Just Google the term "free web hosting" and it will give you a lot of results to choose from.

Here is one that I found on the Internet, the one that I use on one of my websites: https://webfreehosting.net/

As with all free web hostings, there are certain things you can and can't do, such as you can't incorporating your payment application to do ecommerce transactions. To be able to do ecommerce transactions, you'll have to subscribe to their paid hosting service that normally costs about $2.99 per month.

For the free web hosting plan, you are limited to certain bandwidth as well. Not only that, even if you have a paid hosting plan with them and if your website receives a lot of traffic, this hosting provider throttles your bandwidth to slow down your visitors visiting your website, making your website to load very slowly.

An example of that is my website ZeroNilZilch.COM, which receives very heavy traffic, and as a result, this hosting provider throttles my bandwidth, making it very slow to load.

You may have already noticed that the website is very slow to load. This is because my website receives very very heavy traffic and this hosting provider throttles my bandwidth traffic.

So please be patience with my website when surfing my website and please keep visiting my website regularly when you need to. I would love to have you all continue making use of the resources in my website on a regular basis.

Thanks!!!

If you compare ZeroNilZilch.COM with the rest of my websites, say, Noon2Noon.COM, or Rainbow180.COM, or PostalJobHotline.COM, ZeroNilZilch.COM takes a long time to load while the others are very fast to load. This is due to this hosting provider throttles my loading speed because of ZeroNilZilch.COM generating very very heavy traffic.

As you can see, even when I follow their policy very religiously and not even anywhere close to breaking their policy, they still impose limits on my website, something that I'm not very happy about. So this is the only one factor that I'm not happy about this hosting provider.

So please read their policy. Also, you need to abide by their policy on all other aspects of the "free plan" to avoid being shut down. So make sure you read their policy on what you can do and on what you "CAN'T" do.

I hope you take this warning seriously because once you're shut down, you can't get another account with the same host provider. You'll have to find another hosting provider.

All hosting providers have policy that they enforce very strictly. So don't loose your hosting account with this hosting that I mentioned above, because it is one of the best hosting providers out there, albeit, they impose bandwidth limits when your website receives very heavy traffic.

I don't know if other shared hostings do this or not. Anyhow, please be mindful of this scenario.

So good luck and have fun with your website, albeit be mindful of the policies placed on your hosting plan.

A Secret

Here is a secret that no one will tell you about this hosting provider mentioned above, but I will: You can actually signup for many hosting accounts with this hosting provider so that you can host as many (of your) websites as you want.

Yes, that is right; you can have your websites hosted by this hosting provider and it is perfectly legal and they won't ban you for hosting multiple websites on their platform. Yes, that is correct! You can host multiple websites on their platform! I repeat: You can host as many websites as you want on their plaform.

All you have to do is signup each account for each of your websites using a unique email address and it will let you signup for multiple accounts to host multiple websites.

My suggestion for you is to create multiple email accounts, say, with Gmail.COM or with any other email services and using those email addresses to signup hosting accounts with this hosting provider to host all of your websites.

Yahoo Mail is also one of the best emai service providers out there and it on par with Gmail service. I, myself, use both Gmail and Yahoo Mail for my emails needs. I singed up multiple email accounts with both and the best part is that you can signup for an ulimited email accounts.

Remember that one email address is only good for one hosting account to host one website. So if you have multiple websites (as I do), you need to have multiple email addresses so that you can use those email addresses to signup hosting accounts with this hosting provider.

One email address is only good for one website.

You can use (your) same name and same address and the same other information as well.

You don't have to use different name and different other information.

Email address is only one that needs to be unique for each account.

One Last Warning:

Please DO NOT abuse your free hosting priviledges. In other words, please read their 'Users Policies' carefully and obey their rules and guidelines.

Just because it is free and you can signup for multiple accounts, it doesn't mean that you can do anything you feel like doing.

So enjoy your multiple hosting accounts for your multiple websites, but be mindful of their rules and guidelines and DO NOT abuse your priviledges.

There you have it!

A secret that no one will tell you about it!!!

But I am telling you that!!!

So good luck and have fun with your websites, albeit be mindful of the policies placed on your hosting plans.

Navigating Through Your Account Dashboard/Webspace

Once you'd signup an account with the above mentioned webhosting service provider, you can login to your account and the dashboard/webspace looks like the following:

On the left side is where it lists your account detail that looks like the following:

As you can see in the dashboard area or webspace area, you have several options to choose to go into more specific tasks. It shows all kinds of options for you to choose.

For example, when you click on an FTP Manager, it takes you to an FTP manager area where you can setup/create FTP accounts.

From there, you can fill out and supplying the various required FTP account information.

After creating an FTP account, now you're ready to upload your website files to your FTP account.

You will need these FTP account information to be used with your FileZilla application to transfer your files to and from your local computer to your FTP account.

See my other tutorial called Introduction to FileZilla.

Next, you need to create database(s) by clicking on the Database Manager and fill out the appropriate information. You will need these information to use with your database "PDO" connection.

See my other tutorial called Introduction to PDO.

At this point, you're done with creating FTP and Database accounts and presumably all your website files have been uploaded to your FTP account and your database tables and content have been created and setup and ready to go.

Next, you need to setup your domain. Somewhere in your dashboard area, there is a topic called Domain Manager. Click on that topic to go to setup your domain and it opens up a domain creation view that looks like the following:

In the above area where you can setup/create your domain accounts by supplying the necessary information.

There are several options to choose from depending on your actual situation. You can actually buy your own domain from this hosting provider on the spot by clicking on 'register a domain. You can also transfer your domain to this hosting provider if you had registered it with some other domain registrars.

Either way, you're good to go with this hosting provider.

Personally, I recommend you to register your domain with other hosting/domain service providers that can offer you cheap domains. There are plenty of cheap domain service providers out there and one that I use personally is called https://www.namesilo.com/

If you're using domain from other domain service providers, just type the name of your domain in the box under: 'Host an existing Domain', for example: myfirstsite.com. And click on "Host Domain" button. Don't forget to put the "DOT" suffix name after your domain as shown in the example. This can be .com, .net. .org, etc.

If you're using a domain from other domain service providers, make sure that the domain is fully active, otherwise, this hosting is not able to detect your domain from the central server of the World Wide Web consortium who actually is maintaining the domains as a central location.

The domain service providers are just third parties sellers selling domains from the main body organization called the World Wide Web consortium.

After that, it should give you some sort of result at the bottom of your domain space if it is hosted successfully with this hosting provider.

In the result that you just created and hosted successfully, look at the heading at the far right side that says "Settings" and click on that topic. It should slides down to reveal more content. Now click on the topic: "DSN" (stands for 'Domain Name Server') and it should slides down further to reveal more content on that topic.

There are lots of options for you to choose, but for beginners, you only need to be concern with the topic called "NS".

Next, look under the heading called "Type" on the left side and scan down to find "NS" which stands for 'Name Server', or short for 'Domain Name Server'.

You need to copy this domain name server (address) so that you can use it to link your domain that you had registered with other domain service provider to your hosting account with this hosting service provider.

In a simplier way of saying is that, this domain name address is used to link your domain name that is residing in your third party domain registrar to this web hosting provider. Your third party domain registrar needs this information to link the two servers together.

Once you have the domain name server address, you need to go back to your domain service provider that you had registered and had an account with and login to that account so that you can supply this "NS" information to that domain provider.

In your (third party) domain service provider dashboard space, there should be an option that says "Domain Manager" and you need to navigate to that domain manager space and look for some sort of topic called "domain service name entry" or similar to that nature and then supply the "NS" information to it accordingly.

Hint: In your third party domain service registrar, look in the "Domain Manager" and click on one of the options listed on your particular domain. Maybe try clicking on the name of your domain and see what options it reveals.

Different domain service providers have slightly different look and feel, but all of them should have something in common, and that is, a box for you to enter the "NS".

Here is an example of domain entries:

Name Server 1: ns1.example.com

Name Server 2: ns2.example.com

Name Server 3: ns3.example.com

Name Server 4: ns4.example.com

Name Server 5: ns5.example.com

As you can see above, there are several domain name servers that you need to enter, but for most hosting providers like the free web hosting service provider that I mentioned above, you only need to supply only two "NS" entries are enough.

Once you've entered the "NS" information and submitted, it will take about 12 hours to take effect, although some domain providers take longer or shorter.

Meanwhile, after about an hour or so after you've submitted your "NS" information, you can try to load your website to see if it's effective or not. I've found that with most domain service providers, it only takes about one hour to take effect and not more. Try it after an hour of the entry and see if it is effective.

At this point, everything has been covered to enable you beginning website developers to able to create websites and host them in a live server. You can keep making improvements to your websites as they get more sophisticated.

There you have it! Have fun with your websites!


My Coding Convention

First of all, this is my coding convention that I've been using over the years as a programmer, in addition to the PSR-1 and PSR-2, and it works very well for me by combining my own convention with the PSR-2.

Secondly, every programmer should use some sort of coding standard, whether it's PSR-1, PSR-2, my coding standard, or your own coding standard. You definitely should use a coding standard. A programmer who doesn't use a coding standard is a bad programmer and eventually the code that you write will contain bugs.

The ultimate goal of a coding standard is to maintain consistency and readability so that code can be robust, easy to maintain and easy to locate bugs, and can easily be extensible seamlessly by different groups of developers. Consistency is important because it saves time, resources, and money.

Furthermore, in a multi-task organization, it enables a sense of collaroborated code writing and team work where different groups of developers spread all over the world share the same or similar tasks. Since the code is visible to lots of eyeballs, bug-fixing relies on these teeming eyeballs to actually locate bugs and understand how to solve it. A consistent coding standard solves most of that problem.

There are a few coding standards in use out there: PHP's PEAR project has its own, the Zend Framework has one, WordPress has one too, Drupal derives its standard from the PEAR one, and then there is the PSR-1 coding standard (http://www.php-fig.org/psr/psr-1/), along with the PSR-2 coding style guide (http://www.php-fig.org/psr/psr-2/).

PSR-1 and PSR-2, named "Basic Coding Standard" and "Coding Style Guide," were conceived by the PHP Framework Interop Group, an informal group of representatives from major PHP projects, which offers a place to "talk about the commonalities between our projects and find ways we can work together."

This consortium has studied about best practices in PHP to allow developers to have common coding standards. These best practices are called "PHP Standard Recommendations," also known as PSR. So the PSR-1 and PSR-2 are two sets of coding standard.

Note that even though the consortium's main focus was on PHP, but their standard applies to other languages as well; and my coding standard also applies to other languages as well.

Adding into the mix I have adopted my own coding standard, albeit not very extensive, it serves a useful purpose as a 'bugs-avoidance' standard that other coding standard didn't address. Nowaday, the trend is leaving the default legacy style behind and more and more people are adopting new modern style of coding and my coding convention is a byproduct of that new trend. By 'default legacy' style, I mean the typical coding style many of us are getting used to doing. An example of that is:

<?php
class Foo{
  public test($x) {
    if ($x == 1){
    // do something with $x
    }elseif ($x == 2){
    // do something with $x again
    }elseif ($x == 3){
    // do something with $x again
    }else{
    // do nothing with $x
    }
  }

  private getFoo(){
    for ($i = 1; $i < 10; ++i){
      // do something with $i
    }
  }
}
?>
   

Notice how ugly and messy the default old legacy style of coding is? The opening parentheses are placed on the same line as the class and method declaration, and the same thing is also true for loops such as for(), foreach(), while(), and condition code blocks such as if/elseif/else.

It's long past its prime and I'm amazed (or have been amazed for a long time) that this default old legacy style are still being used by the majority of the programming world. Well, I'm glad to see that, nowaday, the programming world are starting to realize that the default old legacy style is showing its old age and more and more people in the programming world are beginning to adopt a new trend of coding style.

I'm among those people who gravitated from the old legacy coding style to this new trend of coding style (some long time ago). The new coding style like mine is the way to move forward and leave the old legacy behind where it belonged.

Here is a preview of the new coding style that makes use of a clean and logical hierarchical levels of indentation:

<?php
class Foo
    {
     private $arr;

     public function config()
          {
           return [
                   'id' => 'app',
                   'basePath' => dirname(__DIR__),

                   'component' => [
                                   'request' => [
                                                 'csrf' => 'csrf-app',
                                                ],
                                   'user' => [
                                              'identity' => 'app\model\User',
                                              'autoLogin' => true,
                                              'cookie' => [
                                                           'name' => 'id-app',
                                                           'httpOnly' => true
                                                          ],
                                              'error' => [
                                                          'action' => 'site/error',
                                                         ],
                                             ],
                                  ],
                  ];
          } // end config()

     public function example($arg1 = null, $arg2 = null)
          {
           if (!empty($arg1))
              {
               // do something with $arg1
               foreach ($arg1 as $item)
                     {
                      // do something with $item
                      try
                          {
                           switch ($item)
                                {
                                 case 1:
                                       // do something
                                       if ($something)
                                          {
                                           for ($i = 0; $i < $something; $i++)
                                               {
                                                $dosomething[$i] = getSomething();
                                               }
                                          }
                                       elseif ($otherThing)
                                          {
                                           foreach ($otherThing)
                                                 {
                                                  try
                                                      {
                                                       $doOtherThing = getOtherthing();
                                                      }
                                                  catch (Exception $e)
                                                      {
                                                       // doOtherThing with $e;
                                                      }
                                                  catch (OtherException $o)
                                                      {
                                                       // doOtherThing with $o
                                                      }
                                                 } // end foreach
                                          } // end elseif ($something)
                                 break;
                                 case 2:
                                      // do something
                                 break;
                                 case 3:
                                      // do something
                                 break;
                                 default:
                                      // do something
                                 break;
                                } // end switch
                          } // end try
                      catch (Exception $e)
                          {
                           // Error! Do something with the error $e
                          }
                     } // end foreach
              } // end if $arg1 is not empty
           elseif ($arg2 != null)
              {
               // do ... while and for() loops
               $test = false;
               do
                   {
                    for ($i = 0; $i < count($arg2); ++$i)
                        {
                         if ($arg2[$i] == 1)
                            {
                             $test = true;
                             break;
                            }
                        } // end for()
                   } // end do
               while ($test == false);
              } // end elseif
           else
              {
               // do nothing
               return '';
              }

           $connect = '';
           $attempt = 3;
           while (!$connect AND $attempt > 0)
               {
                $authConn->connect();
                $connect = $authConn->isConnect();
                $attempt = $attempt - 1;
               }
          } // end example()
    } // end class Foo
?>
   
As you can see from the preview above, the code is much much more cleaner and you can actually follow the hierachical logic of the code flow more easily. Give it a try and keep up with the new trend and leave the old default legacy behind.

Summary: The coding standard aims to achieve three objectives:

  1. Robustness. Robustness should maintain readability, flexibility, consistency, and extensibility that can easily be extensible seamlessly and be well-understood by different groups of developers.

  2. Bug-free. Use sound coding practices to achieve bug-free.

  3. Productivity. Productivity translates more money.
If the first two objectives above is adhered to, these objectives will also gain team productivity because less time is wasted on unnecessary works that should have been done in the first place. If years down the road we constantly are spending time fixing bugs or rewrite codes to suit new tasks instead of just seamlessly extend the app to meet new challenges quickly, that is productivity lost for all teams.

Here is my standard, convention, and guideline that I chose to follow:

I use PHP as a language to illustrate these examples but these standard, convention, and guideline apply to other languages as well.

Code MUST follow all rules and guideline outlined in PSR-1 and PSR-2. However, the following guideline takes precedent over PSR-1 and PSR-2 whenever there are collisions. In other words, I adhere to my own standard and guideline before adhering to other standards. So I get myself familiarized with my own standard and guideline first to make sure that I know when a collision can occur. When a collision occurs I use my own standard over the PSR-1 and PSR-2.

These are my coding standard and guideline:

  1. Naming convention.

    • Use camelCase, not_under_scores_, for class names and function/method names. For example: siteController -- as appose to site_controller; arrayAccessTrait -- as appose to Array_Access_Trait. Avoid using _under_scores_ for single word names as well, for example, using get() as appose to _get(), set() as appose to _set(), unset() as appose to _unset(), etc.

    • Use lower case for file names, even if the name contains multiple words, e.g., myindexfile, privateimagefile. DO NOT use _under_scores_ in file names. This is illegal: my_index_file.php.

    • Use _under_scores_ for variable names, and arguments names. Example: item_1, num_1. Add($annual_salary, $current_bonus).
      See exception below.

    • Always use singular, not plural, for all naming convention. This includes all class, method/function, variable names and directory names.

      For example, addValue() instead of addValues(); getTwoRow() instead of getTwoRows(); getView() instead of getViews(); Theme instead of Themes; ad instead of ads; lib instead of libs; site instead of sites; user instead of users; arg instead of args; item instead of items; and so forth.

      The most popular variables that most programmers use are: views, models, controllers, params, users, items, libs, utils, pages, files, args, lines, rows, images, assets, etc. While it may seems very logical to use plural to name class, method, and variable names to reflect the true description of the variables, it is a very bad idea and it will cause confusions and problems later on.

      Let's face it, we all use proper grammar in our everyday language and it becomes a natural thing to do as well when it comes to programming when naming class, method, and variable names convention. We have a tendency to use proper grammar in our programming work. It's also a habit that is hard to break.

      But it's a habit that we should try to break away from and not following it in programming. So proper grammar is not the best way to program. So please avoid using pluralities. It creates confusions and bugs later on. ALWAYS USE SINGULAR! PERIOD!

    • Use a clear distinct naming convention for all class, method, argument, and variable names. Avoid using the same word as verb/noun to declare two distinct variables, for examples: rate (verb) and rater (noun), use (verb) and user (noun), code (verb) and coder (noun), serve (verb) and server (noun), or even page (noun) and pager (noun), etc. Furthermore, avoid using past tense as well. For example, use connect instead of connected, etc.

      Do not use something like these either: usr and user for two distinct variables; or user/users for two distinct variables (no plural is allowed--only singular); or use/usr/users for three distinct variables; or route/routes/router/routers for four distinct variables (again no plural is allowed--only singular); or use/used/user/users for four distinct variables (again no past tense and plural are allowed).

      If you insist on having the same lexicon in your variables, just add _under_scores and additional variables and some suffix identification to your lexicon word. For examples, user_new_1, user_old_2, user_var_1, route_1, route_2, etc. Just keep in mind that a good naming convention gives less problems later on. A good rule of thumb is, make it very distinct from one another.

    • Exception: Enumerate the naming convention is ok (like: $num1, $num2, $num3, $arr1, $arr2, $arr3, $arg1, $arg2, $arg3, $param1, $param2, $param3, etc.); however, please try to limit its use to an absolute minimum.

    • Class Constants: Class constants must be all upper case letters (e.g., DEMO, PROFILE, DASHBOARD) and if multiple words are used (e.g., DEV_DEBUG, EVENT_BEFORE_ACTION, CORE_ROOT_DIR) _under_scores_ must be used to seperate the multiple words. Notice that the word dashboard is considered as a single word.

    • camelCase: A camelCase is when you have multiple words as one word and that word begins with a lower case letter for the first sub-word and the rest of the sub-words' initial letter are upper case letters. For examples, the word 'camel case' becomes camelCase; the word 'error exception trait' becomes errorExceptionTrait; the word 'my product category list' becomes myProductCategoryList.

    • Use lower case for the most part except when camelCase is warranted. And for single-word method/function, class names can be an upper case letter for the beginning letter and the rest are lower case letters. Or it can be all lower case letter but cannot be all upper case letters. For example, these are ok: Add(), add(), but these are not allowed: ADD(), $ITEM, $PARAM, $LIB, etc.

      If you use an upper case letter for the initial letter of the single-word names, make sure to stick to that convention and if you use lower case for the initial letter of the single-word names, also be consistent and stick to that convention as well. Be consistent!

    • Important: Failure to adhere to these naming convention and other guidelines outlined in here can cause your code to contain bugs later on.

    • Naming a file name the same as its class name. For example, class errorExceptionTrait has its file being named as errorexceptiontrait.php. For any other files, they don't have to have the same name.

    • Naming all folder names without using _under_scores_ even if there are multiple words. For example, naming your folders as AdminController as appose to Admin_Controller, VendorComponent as appose to Vendor_Component, LibUtil as appose to Lib_Util, etc. No plural is allowed as well. So name your folders as image as appose to images. Yes, it seems like overwhelming majority of programmers like to name their folders as 'images' as appose to 'image' because it makes a logical sense to name their folders using plural to hold images. Always use singular. Period! No 'and', 'if', or 'but'.

    • Summary: So the key point to remember is that ONLY variables can contain _under_scores_. Anything else cannot contain _under_scores_.

    • Always comment your class, method, and function ending demarcations if your code is lengthy. For shorter code, you can go without the comment. This helps you and others follow the logic of your code. For example, assuming you have a lengthy code:

      <?php
      class Foo
          {
           public addValue($x, $y)
                {
                 // method body
                } // end addValue()
      
           private getFoo()
                 {
                  // method body
                 } // end getFoo()
          } // end class Foo
      
      ?>
      Notice the comments: // end addValue(), // end getFoo(), // end class Foo
         

    • Always comment your condition blocks ending demarcations if your code is lengthy. This includes: if/else/else if/ and other condition blocks such as while, do ... while, and for loop blocks such as for() and foreach(), and for try ... catch() blocks as well. For shorter code, you can go without the comment. This helps you and others follow the logic of your code. For example, assuming you have a lengthy code:

      <?php
      class Foo
          {
           if ($expr1)
              {
               // lengthy multiple statements code block
               // lengthy multiple statements code block
               // lengthy multiple statements code block
              } // end if ($expr1)
           elseif ($expr2)
              {
               // lengthy multiple statements code block
               // lengthy multiple statements code block
               // lengthy multiple statements code block
              } // end elseif ($expr2)
           else
              {
               // lengthy multiple statements code block
               // lengthy multiple statements code block
               // lengthy multiple statements code block
              } // end else if ($expr2)
      
           try
               {
                // lengthy multiple statements code block
                // lengthy multiple statements code block
                // lengthy multiple statements code block
                // lengthy multiple statements code block
               } // end try block
           catch (Exception $e)
               {
                // lengthy multiple statements code block
               } // end Exception $e
           catch (OtherException $o)
               {
                // lengthy multiple statements code block
               } // end OtherException $o
          } // end class Foo
      ?>
      Notice the comments:
           // end if ($expr1), // end elseif ($expr2), // end else if ($expr2)
           // end try block,   // end Exception $e,    // end OtherException $o
           // end class Foo
         



  2. Killing Tabs. When you indent your code (or line statements) make sure to kill all tabs; because if you don't, the indentation that contains tabs will not aligned properly from one editor to the next if you use multiple editors. Yes, all of us use different editor all the time. Furthermore, even the same editor that you use regularly will behave differently if you upgrade its version from one version to the next. So make sure to kill all tabs. Period!

    Tabs are text editor's special feature that enable you to speed up the moving of spaces by skipping the individual space when you press the "tab" button or the "advance forward" horizontall bar or the "return" key (or bar).

    In other words, when you press the "return" key the editor will jump pass the beginning of the line to the level that the immediate previous line starts, so that the beginning line of your code align with the beginning line of the previous line. All editors have this feature to save time of moving the beginning of your line to align it with the beginning of the previous line.

    Contrary to popular opinions, this so called "speed up" feature of the editors is actually slowing down the over all productivity of your finished (programming) products.

    How so? For one, if you're familiar with the Python programming language, you know that tabs can and do alter the meaning of the code you are writing; second, some Javascript interpreters see tabs as foreign objects and behave un-expectedly. There are other bad behaviors that tabs can cause your programing code to slow down your productivity and I don't want to list them here and only want to hi-light a few to let you know that tabs in programming generally is bad.

    So you don't want this default feature of the editor to mess your indentation by not killing them. So always kill all tabs.

  3. Shorthand Arrays. Shorthand array syntax [...elements...] is used instead of the regular long form array(...elements...). And (shorthand) arrays used in the configurations can optionally contain a comma (",") as well at the end of the array element list. As examples, the below configurations contain a comma following the last array element [particularly 'charset => utf8' for shorthand array] even though there isn't another array element following it.

    As a matter of fact, both regular arrays and shorthand arrays can contain a comma (",") at the end of the array element list. This is legal (for both) and you can choose to put it there or take it out and it is perfectly fine. It's not a requirement to have a comma at the end of the last array element. So it's up to your personal preference.

    However, this coding standard strongly recommends putting a comma after all array elements because it avoids bugs. The reason that it is legal to have a comma after the last array element is to speed up coding process and avoid bugs. So it is strongly suggested that you put a comma after the last array element to avoid bugs.

    Here is a snippet of code using the regular array:

    $requirement = array(
                         array(
                               'name' => 'PHP Some Extension',
                               'mandatory' => true,
                               'condition' => extension_loaded('some_extension'),
                               'by' => 'Some application feature',
    
                               // notice the comma after this last array element!
                               'memo' => 'PHP extension "some_extension" required',
                              ),    // <== notice the comma! this is perfectly legal!
                        );
    

    In the following, a configuration is used to create and initialize a database connection. Notice the comma following the array element 'charset => utf8' even though there isn't another array element following it:

    $config = [
               'class' => 'core\db\Connection',
               'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
               'username' => 'root',
               'password' => '',
               'charset' => 'utf8',  // <== notice the the comma! it's perfectly legal!
              ];
    $db = core::createObject($config);
    

    If you look at the example preview earlier [in the function config()], you'll see shorthand arrays are being used and all last elements of the arrays have a comma after each of the last element of the arrays. So it is definitely recommended that shorthand arrays and a comma on the last element of the array are being used -- on your own programming chores -- because it is much cleaner and easier to visualize, and most importantly, it speeds up your application development by eliminating bugs and unnecessary syntax corrections.



  4. Readability. There must be a space between variables and arithmetic signs/operations, comment demarcation, comparison/assignment operations. For examples:

       $a = $b + $c; // add b to c
       Do not do this: $a=$b+$c; //add b to c
    
       if ($b == $c)
       Do not do this: if($b==$c)
    
       Do not do this: for($i=0;$i<10;$i++)
       Do this instead: for ($i = 0; $i < 10; $i++)
       

  5. Class and function hierarchical structures and indentations

    Most modern coding conventions indent only four spaces for all code hierarchical structures, and because keywords have different lengths, it causes the hierarchical levels of indentation to look weird and not very clean. For example, to indent four spaces for the class, it looks like this:

    class Example
        {
        }
    
    That looks very good, but on longer reserved/keywords like public, private, protected, static, etc., it looks awful. For examples:

    public class Example
        {
        }
    
    private class Example
        {
        }
    
    protected class Example
        {
        }
    
    static class Example
        {
        }
    
    Or for conditional structures:
    
    if (condition)
        {
        }
    else
        {
        }
    elseif
        {
        }
    
    foreach
        {
        }
    As you can see, indenting four spaces for all code structures, [although very uniformed], is a bad idea, and it looks weird visually and logically. That's why I chose to indent the code according to the length of the reserved keyword.

    For a better view of the examples of hierarchical structures and indentations that make use of the reserved keywords, see the preview example earlier or the following examples.

    The guidelines for class and function structures and indentations follow what I call a common sense rule, and that is, the placement of parentheses, spaces, indentations, and braces are placed based on the position of the clause either at the end of the keyword or one space after the keyword in the case for short keywords.

    For long keywords like abstract, private, protected, etc. (public is o.k.), you can indent just five positions to align with 'public' and it's fine. Although indent the full keyword is o.k., too. See examples for a better visualization.

    DO NOT place the opening parenthesis on the same line as the class, method definition, and do not place the closing parenthesis on the same line as the last statement. The opening and closing parentheses should be aligned vertically and indented the exact amount of spaces. The following is the default, old fashion style of coding. It's past its legacy. So don't do this:

    class Example {
         private $myVar;
    
         public myMethod($x) {
          // ... code
          return $x; }
    
         // ... more class code here!
    }
    
    Nowaday, the trend is leaving the legacy style behind and more and more programmers are adopting new modern style of coding and my coding convention is a byproduct of the new trend. So do these instead:

    <?php
    class Foo
        {
         /**
          * class body declaration.
          * notice the four spaces indentation of the class' opening "{" and
          * the five spaces indentation of the method declaration: public.
          * notice also that the opening/closing parentheses are aligned vertically at the
          * same level, and all respective code body are inside the parentheses.
          * it looks very clean and easy to follow the logic of the code flow.
          */
         public $arr = array();
         private $dbConnection;
    
         public addValue($x, $y)
              {
               // method body
               // notice that the indentation and placement of the opening "{" and
               // closing "}" directly leveled with the last letter of its keyword.
              }
    
         private getFoo()
               {
                // method body
                // notice that the indentation and placement of the opening "{" and
                // closing "}" directly leveled with the last letter of its keyword.
               }
    
         protected getBar()
                 {
                  // method body
                  // notice that the indentation and placement of the opening "{" and
                  // closing "}" directly leveled with the last letter of its keyword.
                 }
    
         // this is ok, too, and is preferred, indent five spaces to align with
         // 'public' which is the most commonly use visibility clause
         protected setFoo($x)
              {
               // method body
              }
    
         public addFoo()
              {
               // method body
              }
    
         // this is ok
         abstract protected function zeroBar();
                {
                 // method body
                }
    
         // this is ok, too, indent five spaces to align with 'public' which is
         // the most commonly use visibility clause
         abstract arrayHelper()
              {
               // code body here for this abstract method
              }
    
         public static function bar()
              {
               // method body
              }
    
         // this is ok, too
         private static function bar()
               {
                // method body
               }
    
         // this is ok, too, indent five spaces
         private static function bar()
              {
               // method body
              }
    
         final public static function bar()
             {
              // method body
             }
    
         // same as above
         final private static function bar()
             {
              // method body
             }
    
         static function bar()
              {
               // method body
              }
    
         // this is ok, too
         function bar()
                {
                 // method body
                }
    
         // this is ok, too, indent five spaces to align with 'public'
         function bar()
              {
               // method body
              }
    
         // this is ok, too, because it has at least five spaces indented for body code
         function bar()
         {
               // code body.
               // notice the placing of "{}" at the same level as the method declaration.
               // notice also the indented five spaces for coding statements
               // starting position
               // .....
         }
        } // end class body
       ?>

    Notice that the parentheses are aligned vertically at the same level of indentation. This applies to all other code blocks/structures that contain parentheses, e.g., if/elseif/else, for() and foreach() loops. This makes it very easy to visualize the block of code, especially if the code is very lengthy.

    Note also that the examples showed multiple styles of indentation, but you need to decide which one is more suited to your style and stick with it consistently and do not use one variation for certain project and another for another project. Be consistent and choose one style and stick with it for the long haul.

    Traits: Traits are special form of class and they are similar to a normal class.

    trait ArrayHelper
        {
         // main body code of a trait
        }
    CSS: For CSS and other languages (such as Javascript, Java, C#, C/C++, etc.) do follow the guideline outlined in this coding standard and follow a five-space rule to align with 'public' visibility clause. For examples:

    <style>
    html,
    body
        {
         width: 100%;
         height: 100%;
         background-color: #e6e6ff;
        }
    
    #product-item
        {
         background-color: white;
         padding-left: 10px;
         padding-right: 10px;
        }
    
    div .some-selector
        {
         background-color: white;
         width: 400px;
         height: 200px;
        }
    
    .nav li > form > button.logout
        {
         padding: 15px;
         border: none;
        }
    
    a.asc:after, a.desc:after
        {
         position: relative;
         top: 1px;
         display: inline-block;
         font-family: 'Glyphicons Halflings';
         font-style: normal;
         font-weight: normal;
         line-height: 1;
         padding-left: 5px;
        }
    
    a.asc:after
        {
         content: "\e151";
        }
    
    a.desc:after
        {
         content: "\e152";
        }
    </style>
    
    <script type="text/javascript">
    $(document).ready(function()
        {
         public function example(arg)
              {
               // function code
              }
    
         // this is ok, too
         function example(arg)
                {
                 // function code
                }
    
         // this ok, too, to align with 'public'
         function example(arg)
              {
               // function code
              }
    
         // this ok, too
         static public function example(arg)
              {
               // function code
              }
        });
    </script>
     

    Notice the braces are aligned vertically and indented at the same amount of spaces (5).

    HTML: Always use lower-cased letters for HTML tags with the exception of the doctype interface. The heading code (or tags), e.g., meta, link, script, etc need not be indented but the css, javascript code, and the code inside the body tag MUST be indented of at least three spaces and can be indented up to six spaces. For example:

    <!DOCTYPE html>
    <html lang="en-US">
    <head>
    <title>Untitled</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" >
    <link href="./asset/44ab1983/css/style.css" rel="stylesheet">
    <script src="./asset/16eb9947/jquery.js"></script>
    <style>
    html,
    body
        {
         width: 100%;
         height: 100%;
         background-color: #e6e6ff;
        }
    
    #product-item
        {
         background-color: white;
         padding-left: 10px;
         padding-right: 10px;
        }
    </style>
    
    <script type="text/javascript">
    $(document).ready(function()
        {
         public function example(arg)
              {
               // function code
              }
        });
    </script>
    
    </head>
    
    <body>
         <div>
             content of the div
         </div>
    
         <div>
           <table>
             <tr>
               <td>
                 td content
               </td>
             </tr>
           </table>
         </div>
    
         <div>
           content of the div
           <a href="#">link</a>
         </div>
    </body>
    </html>
    

  6. Control hierarchical structures

    For a better view of the hierarchical structures and indentations, see the preview example earlier.

    if, elseif, else

    An if structure looks like the following. Note the placement of parentheses, indentation of spaces, and braces; and that else and elseif are aligned vertically on different lines as the closing brace from the earlier body. Notice also the use of braces to group a single statement even though it is not required. Doing so improves readability and eliminates unforced errors.

    DO NOT place the opening parenthesis on the same line as the condition expression, and do not place the closing parenthesis on the same line as the elseif/else condition expression. This applies to other control clauses as well, such as foreach, while, do ... while, etc.

    <?php
    if ($expr1)
       {
        // single statement block. notice the use of braces even though it is not required!
       }
    elseif ($expr2)
       {
        // elseif code block. single statement block
       }
    elseif ($expr3)
       {
        // multiple statements code block
        // multiple statements code block
        // multiple statements code block
       }
    else
       {
        // else single statement block code block
       }
       

    switch, case

    A switch structure looks like the following. Note the placement of parentheses, indentation of spaces, and braces. The case statement MUST be indented for the length of the keyword 'switch' from switch, and the break keyword (or other terminating keyword) MUST be indented at the same level as the case block. Statements inside the case block MUST indent to the start if case condition's first position. For example, if case 0, the indentation of the case statements should align vertically with '0'. There MUST be a comment such as // no break when fall-through is intentional in a non-empty case block (see case 1, 2, 3, 4). Notice that there are no break clauses in any of them.

    DO NOT place the opening parenthesis on the same line as the switch condition expression, and do not place the closing parenthesis on the same line as the last break clause of the switch clause. This applies to other control clauses as well, such as foreach, while, do ... while, etc.

    <?php
    switch ($expr)
         {
          case 0:
               echo 'First case, with a break';
          break;
          case 1:
               echo 'Second case, which falls through';
               // no break
          case 2:
          case 3:
          case 4:
               echo 'Third case, return instead of break';
               return;
          default:
               echo 'Default case';
          break;
         }
       

    while, do while, for, foreach, try, catch

    The guidelines for all these clauses are basically identical to one another and follow what I call a common sense rule, and that is, the placement of parentheses, spaces, indentations, and braces follow the guidelines outlined thus far. So looking back at the indentation of the switch clause we can see that the indentation is to the length of the keyword 'switch'. This applies to the rest of the clauses as well. So a while statement looks like the following. Note the placement of parentheses, spaces, indentation of spaces, and braces. The braces are all on seperate lines from the clause, even for a (do ... while) condition.

    <?php
    while ($expr)
        {
         // structure of code block
        }
       

    Similarly, a do while statement looks like the following. Notice the placement of braces.

    <?php
    do
     {
      // structure of code block;
     }
    while ($expr);
       

    It can also be like the following as well. Notice the placement of braces which aligned directly with the end of the keyword 'while'.

    <?php
    do
        {
         // structure of code block;
        }
    while ($expr);
       

    A for() loop structure is also identical to other condition clauses and follow what I call a common sense rule that looks like the following. Note the placement of parentheses, spaces, and braces. Notice the indentation to the first position after a space following the keyword 'for'. This rule applies to try, and catch as well but not to foreach() in which it indents to the last position of the keyword 'foreach'.

    <?php
    for ($i = 0; $i < 10; $i++)
        {
         // for code block
        }
       

    A foreach statement looks like the following. Note the placement of parentheses, spaces, and braces. It indents to the last position of the keyword 'foreach'.

    <?php
    foreach ($iterable as $key => $value)
          {
           // foreach code block
          }
       

    A try...catch block looks like the following. Note the placement of parentheses, spaces, and braces. The braces indents one space past the last position of the keyword 'try' to align the braces of the 'catch' clause.

    <?php
    try
        {
         // try code block
        }
    catch (FirstExceptionType $e)
        {
         // catch code block
        }
    catch (OtherExceptionType $e)
        {
         // catch code block
        }
       

  7. Closures

    Closures MUST be declared with NO space after the function keyword, and a space before the use keyword, but no space after the use keyword.

    The opening brace MUST go on a seperate line as is typically for all braces, and the closing brace MUST go on the next line following the body as is typically for all braces.

    There MUST NOT be a space after the opening parenthesis of the argument list or variable list, and there MUST NOT be a space before the closing parenthesis of the argument list or variable list.

    In the argument list and variable list, there MUST NOT be a space before each comma, and there MUST be one space after each comma. Closure arguments with default values MUST go at the end of the argument list.

    A closure declaration looks like the following. Note the placement of parentheses, commas, spaces, indentations (five spaces) and braces:

    <?php
    $closureWithArg = function($arg1, $arg2)
         {
          // body
         };
       

    Or you do this:

    <?php
    $longArg_noVar = function(
                              $longArgument,
                              $longerArgument,
                              $muchLongerArgument
                             )
         {
          // code body
         };
    
    $noArg_longVar = function()
         use(
             /* notice naming variables using enumerated variables, */
             /* although $longVar1 is fine */
             $longVar1,
             /* notice naming variables using enumerated variables, */
             /* although $longVar2 is fine */
             $longerVar2,
             /* notice naming variables using enumerated variables, */
             /* although $longVar3 is fine */
             $muchLongerVar3
            )
         {
          // code body
         };
    
    $longArg_longVar = function(
                                $longArgument,
                                $longerArgument,
                                $muchLongerArgument
                               )
         use(
             // readability: indents some spaces
             $longVar1,
             $longerVar2,
             $muchLongerVar3
            )
         {
          // code body
         };
    
    // this is ok too
    $longArg_shortVar = function(
                                 $longArgument,
                                 $longerArgument,
                                 $muchLongerArgument
                                ) use($var1)
         {
          // code body
         };
    
    // this is ok, too
    $shortArg_longVar = function($arg) use(
                                           $longVar1,
                                           $longerVar2,
                                           $muchLongerVar3
                                          )
         {
          // code body
         };
       

    Note that the formatting rules also apply when the closure is used directly in a function or method call as an argument.

    <?php
    $foo->bar(
              $arg1,
              function($arg2) use($var1)
                  {
                   // code body
                  },
              $arg3
             );
       

    A Brief Few Words About the Use() Function

    Use() is a PHP special function that allows the passing of anonymous function argument variables into the code block of the closure. For example, in the above closure, use() contains one argument called $var1 and this $var1 argument variable is passed in from the outside and gets used by the anonymous function.

    If you look at the next one up from the one above, that use() contains three argument variables called $longVar1, $longerVar2, and $muchLongerVar3, and these three argument variables are passed in from the outside. For more on user(), please checkout PHP documentation.

    The following are not my coding standard -- they are from PSR-1 and PSR-2, and if overlapping, my coding standard above should take precedent and override these third-party standards. If any standard in these two versions, PSR-1 and PSR-2, are overlapping, PSR-2 takes precedent over PSR-1.

    Please visit their website for more. Here is a summary of the third-party standards.


  8. Third-Party Standards

    PSR-1 - Basic Coding Standard
    PSR-2 - Coding Style Guide

    Introduction

    Some noteworthy rules:

    Use camelCase, not_underscores, for variable names, function names, method names, and arguments names.

    PSR-1 - Basic Coding Standard

    Files MUST use only UTF-8 without BOM for PHP code.

    Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.

    Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].

    Class names MUST be declared in StudlyCaps.

    Class constants MUST be declared in all upper case with underscore separators.

    Method names MUST be declared in camelCase.

    Namespace and Class Names

    Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].

    This means each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name.

    Class names MUST be declared in StudlyCaps.

    Code written for PHP 5.3 and after MUST use formal namespaces.

    For example:

    <?php
    // PHP 5.3 and later:
    namespace Vendor\Model;
      
    class Foo
        {
    	 // code block
        }
       

    Code written for 5.2.x and before SHOULD use the pseudo-namespacing convention of Vendor_ prefixes on class names.

    <?php
    // PHP 5.2.x and earlier:
    class Vendor_Model_Foo
        {
    	 // code block
        }
       

    Class Constants, Properties, and Methods

    The term "class" refers to all classes, interfaces, and traits.

    Constants

    Class constants MUST be declared in all upper case with underscore separators. For example:

    <?php
    namespace Vendor\Model;
      
    class Foo
        {
         const VERSION = '1.0';
         const DATE_APPROVED = '2012-06-01';
        }
       

    Properties

    This guide intentionally avoids any recommendation regarding the use of $StudlyCaps, $camelCase, or $under_score property names. Whatever naming convention is used SHOULD be applied consistently within a reasonable scope. That scope may be vendor-level, package-level, class-level, or method-level.

    Methods

    Method names MUST be declared in camelCase().

    PSR-2 - Coding Style Guide

    Overview

    • Code MUST follow a "coding style guide" PSR [PSR-1].

    • Code MUST use 4 spaces for indenting, not tabs.

    • There MUST NOT be a hard limit on line length; the soft limit MUST be 120 characters; lines SHOULD be 80 characters or less.

    • There MUST be one blank line after the namespace declaration, and there MUST be one blank line after the block of use declarations.

    • Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.

    • Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.

    • Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility.

    • Control structure keywords MUST have one space after them; method and function calls MUST NOT.

    • Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.

    • Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before. Example

      This example encompasses some of the rules below as a quick overview:

      <?php
      namespace Vendor\Package;
        
      use FooInterface;
      use BarClass as Bar;
      use OtherVendor\OtherPackage\BazClass;
        
      class Foo extends Bar implements FooInterface
          {
           public function sampleFunction($a, $b = null)
                {
                 if ($a === $b)
                    {
                     bar();
                    }
                 elseif ($a > $b)
                    {
                     $foo->bar($arg1);
                    }
                 else
                    {
                     BazClass::bar($arg2, $arg3);
                    }
                }
      
           final public static function bar()
               {
                // method body
               }
          }
         


What is the difference between a class and an object ?

Both class and object have the same meaning and both achieve the same purpose but differ only in the way they're implemented and used.

A class consists of constant variables, properties, and methods. Those are the three basic attributes of a class. That's all a class is: it has three attributes -- a very simple concept and yet very powerful.

Consider the following class definition:

<?php
class MyClass
    {
     // 1st attribute of the class (MyClass):
     // declaring class constant variables
     // COMMAND_EVENT_START, COMMAND_BEFORE_START,
     // COMMAND_AFTER_START are constant variables
     // command_start, before_start, after_start are constant values

     const COMMAND_BEFORE_START = 'before_start';
     const COMMAND_EVENT_START = 'command_start';
     const COMMAND_AFTER_START = 'after_start';

     // 2nd attribute of the class (MyClass):
     class properties: properties must be declared prefacing with visibility control
     public, protected, private are visibility control:

     public $make = 'Toyota';
     protected $model = 'Tundra';
     private $color = 'grey';

     // 3rd attribute of the class (MyClass):
     class methods: methods must be declared prefacing with visibility control
     public, protected, private are visibility control:

     public function test1()
          {
           // will output: An object is just a copy of the class.
           echo "An object is just a copy of the class." . "\n";
          }

     public function test2($str)
          {
           // will output whatever string got passed in via $str
           echo $str . "\n";
          }
    }
?>

And then consider this object creation:

$str = 'An object is just a copy of the class.';

creating an instance of MyClass()
$obj is an instance of the class MyClass. it is a copy or a clone of MyClass.
$obj = new MyClass();

$obj->test1($str);
will output an error message saying argument $str is undefined in test1().

$obj->test1();
will output ---->  An object is just a copy of the class.

$obj->test2();
will output an error message saying test2() requires at least one argument.

$obj->test2($str);
will output -----> An object is just a copy of the class.

A class is the program you write (i.e., the MyClass class implementation above); while object (i.e., $obj) is the copy of the class or the clone of the class, most often being known as the instance of the class.

A class resides in ROM (permanent memory area) whereas object (i.e., $obj) resides in RAM (temporary memory area.)

In ROM, data is stored there permanently even when the computer is turned off. In a RAM memory area, on the other hand, data get stored temporarily while the program is running or while the computer is still turned on. When the computer is turned off, the RAM data (i.e., $obj) is completely erased and is no longer stored in the RAM.

Instances of a class can be useful only while the program is running or while the computer is turned on; and when the program is not running or when the computer is turned off, instances of a class are no longer useful to a program, and, therefore, it is stored in a temporary memory area.

Instances of a class can be created 'on the fly' at any time when needed by a program [as you can see above: $obj = new MyClass()].

Instances of a class are often being created from everywhere when needed (i.e., libraries, frameworks, and other classes, etc.)

So there is no need to store instances of a class permanently in permanent memory spaces and wasting valuable memory spaces.


What is a FileZilla ?

A FileZilla is a program that transfers files to and from a server. In other words, FileZilla can transfer files from your computer to a server and as well as can download files from that server back to your computer.

It is typically being used by website owners who need to upload their website files from their local computer to a remote server that their website is hosting on. You can also use FileZilla to download files from a remote server that your website is hosting on as well.

So it is a file transfer application using an FTP file transferring protocol. So FTP is an acronym for File Transfer Protocol.

As always, lots of tutorials on this subject are available on the Internet, particularly on YouTube and elsewhere in HTML. So instead of actually doing a tutorial that can be found easily on the Internet, I'm going to just refer you to those tutorials and let you follow those tutorials instead. Why is there a need for me to do a tutorial that is readily available on the Internet? The answer is that absolutely no!

So here we go:

Introduction to FileZilla

How to use FileZilla

How to use FileZilla

How to use FileZilla

Here are brief summaries of steps on how to configure FileZilla client after you'd watched tutorials listed above and as well as having FileZilla downloaded and installed onto your computer.

  1. Download the FileZilla onto your computer.

  2. Once you've downloaded it, extract it using zip extracting applications like WinZip Express Zip WinRAR or WinRAR here! PeaZip

  3. Collecting FTP Details

    After you installed FileZilla onto your local computer, you now are ready for the transferring process. But first thing first, you need to gather the FTP details of your hosting account. Each hosting provider is different in how they layout their FTP information. For Hostinger users, the information is located in the hPanel's menu, under:

    Files -> FTP Accounts

    Most hosting providers have a dashboard area or webspace area where you can see options to choose to go into more specific tasks. For example, for my hosting provider, it has a dashboard that shows all kinds of options for me to choose. For example:

Here, when I click on an FTP Manager, it takes me to an FTP manager area where I can setup/create FTP accounts. In the FTP manager I can create an account by creating a username and a password. I will need these information that I created to be used in the FileZilla. Here is what the inforamtion in the FTP manager looks like:

Once you have an FTP information, you can use it to configure FileZilla. Now all you have to do is click on your FileZilla icon to open it and you'll see a screen that looks like the following:

As you can see in the diagram above, on the left side is for a local working area or section. This is where you can configure your connection information and selecting files or directories to upload to a destination on the right side. On the right side is a remote site or destination area to upload to.

In the above diagram, you can provide information to do a "quick connect" connection. However, I strongly suggest that you don't use a quick connect but instead go through a longer connect, which I will detail it for you. It will save you time later on. A quick connect doesn't remember your connection setting after your computer is turned off, while a longer connection will.

Here is for the longer and more efficient connection:

Click on "File" at the top left corner of the diagram shown above. The drop-down menu will reveal several options but you want to choose "Site Manager" option. A site manager screen should open up and should looks like the following:

Pay close attention to a section called "Select Entry" where all of your FTP accounts are to be created. In my case, I have four FTP accounts: one account to connect to a Monday-Sunday website FTP hosting account; another to connect to a Noon2Noon.NET FTP hosting account; another to a Postal FTP hosting account; and finally to a ZeroNilZilch FTP hosting account.

So in my case, I have four different hosting service providers, and, therefore, I need to have four different entry names (Monday-Sunday, Noon2Noon.NET, Postal, ZeroNilZilch), each connecting to its individual FTP account.

So in your case, the "Select Entry" section and "My Sites" area should be empty because you haven't create a "New Site" yet.

To create a "New Site" entry name similar to the four shown in my case, click on another option called "New Site" down below at the bottom of the diagram. Once you click on "New Site" option, an entry inside the "Select Entry" under "My Sites" area will appear for you to enter an entry name similar to the four entry names that I've created.

Name your entry name any name you like. It's just a name to differentiate from one entry name to another.

Once you created an entry name, you need to configure FileZilla to connect to your FTP hosting account by hi-lighting an entry name similar to what is shown with ZeroNilZilch right now. As you can see, once you hi-light it, the entire diagram flickers and changes the configruation and reveals input boxes for you to enter an FTP information.

For example, for me, I hi-lighted or selected 'ZeroNilZilch' in the "Select Entry" section, and then to the right, I entered 'zeronilzilch.com' in the host box.

This information is obtained from my FTP hosting account created earlier. In your case, you can get this information and the rest of the FTP information from your FTP hosting account.

For port, I use 21, which is a common port for a shared hosting. All you need to know about port is that if you rent or use a free web hosting from any vendor, use port 21, because most likely they're shared hosting. All shared hostings use port 21.

For protocol, select FTP; for encryption select FTP over TLS (just like what it looks like on the screen); for logon type, use 'Normal'; for user (or username) enter the actual FTP username you got from your hosting vendor; likewise, for the FTP password.

That is it! Nothing else to enter. Very easy! Now all you have to do is click on the button "Connect" to connect to your FTP hosting server to begin the transfer process.

After you click on "Connect" it should looks similar to the partial diagram shown below. I show only partial diagram to avoid revealing my other information to the public. But this partial diagram should give you a good idea of how it works.

As you can see, it is very easy to use FileZilla.

Now since you've created your connection the longer and more efficient way, next time you need to connect to your FTP account, just open up your FileZilla application that should looks like the default view similar to the one that has a "quick connect" option on it (shown earlier).

Yes, that is the default view of FileZilla (shown earlier) allowing you to either do a "quick connect" or do a longer more efficient connect.

So since you went through a series of steps to do a longer and more efficient connect already, now all you have to do is click on one of two things:

  1. First the hard way:

    You can click on "File" at the top left corner of the diagram shown above. The drop-down menu will reveal several options but you want to choose "Site Manager" option.

    A site manager screen should open up and should looks like the "Site Manager" diagram shown earlier. From there, all you have to do is hi-light an entry name to make it looks like the one shown on "ZeroNilZilch." This will activate your FTP account setting and ready to be connected to. Next, just click on the "Connect" button and it will try to connect to your FTP hosting account.

    Well, that was somewhat the hard way. Sort of!

  2. Now the easy way:

    The same thing: you can click on "down arrow" or a drop-down menu just below "File" at the top left corner of the diagram shown above. The drop-down menu will reveal an entry name (or several entry names if you have more than one as in my case).

    Now all you have to do is click on an entry name in the drop-down menu and a "Site Manager" showing your entry name is shown ready to be connected to your FTP hosting account. Next, just click on "Connect" button and it will try to connect to your FTP hosting account.

Once connected it should looks something like a partial diagram shown below.

Since it is a partial listing of the actual full view, you're not able to see all options you can do with the connection. You'll have to make use your FileZilla on your own from here on. It is very easy because all the hard part has been explained and now is just the easy part.

Well actually, you can see a somewhat full view of the default view shown earlier and you should get a good idea of how you can select a particular file or directory to upload to.

But briefly, as you can see from the above diagram, there are two parts: one on the left side contains your local file directories where you can select and upload them to the destination on the right side. Simple enough?

On the left, because of a partial listing, I am not able to show you that you can actually select or pull down a drop-down menu to select any directory from your local computer to upload to the destination on the right side. Yes, you can select or pull down a drop-dwon menu on the left side and select any directories or files to upload to the destination on the right side.

Likewise, on the right side, you can select (or pull down a menu--well, mainly select) a directory to receive the content being uploaded to it. In other words, to upload a file or files or directory or directories, you need to know where in directory destination you want to upload the content from the left side to on the right side. Self-explanatory!

Once you've selected the destination directory on the right, and then you can go ahead and upload the content on the left side by hi-lighting or selecting it and right-click it to reveal several options. One of the options is "upload" and select "upload" to upload it. Self-explanatory!

Likewise, on the right, you select a particular file or files or directory or directories by hi-lighting it and then right-click it to reveal several options. One of the options is "download" and click on it to download. Self-explanatory!

That is it! Have fun using FileZilla.


A very brief introduction to one of the most important and valuable pattern programming methodology that ever developed in the programming world: MVC

What is an MVC ?

An MVC is an acronym for Model View Controller.

It is a methodology to uniform the way people program applications. Remember that in programming, programmers tend to have their own unique way of doing things and that causes a lot of confusions, especially in a team work where programmers are working in the same project. There is no way of knowing what each programmer is trying to do in the same project. There is a compatibility issue.

There is no uniform pattern way of doing things; each programmer is doing things each his/her own way of doing things; for example, in a team work in the same organization working on the same project, one programmer puts data handling with the organization of that data while another programmer puts the same data handling with the displaying of that data to users; and the two programmers are completely oblivious to what the other programmer is trying to do.

This causes the finished product to be in-efficient, in-compatible, and not robust and not to mention the cost of having programmers to do other similar projects that take a long time to complete because of the codes are not re-usable.

So to be efficient, robust, scalable, upgradable, re-usable, and easy to maintain, it has to be a unique way of doing things for all programmers to understand and work in a uniform way so that all programmers can know systematically what the other programmers are doing in the same project, even if each programmer is located far away from each other and haven't seen each other's actual work.

To solve this issue, the MVC was developed.

To understand the concept of MVC, think of it in term of an organization mentioned above where there is a manager, some programmers, and the customers who want to get the application done.

The customer is the view presenting to the manager of what to be done, telling the manager the criterio of what need to be done. For example, the customer may wants the website that has ecommerce and social media applications capability installed in it.

The manager is the controller, handling the organization (or criterio) of the task dictating and given by the customer.

The programmers are the model handling of data or instructions given by the manager and using those instructions from the manager to proceed to do all of the programming work.

Notice that the manager, or the controller, does not know how programmers perform their tasks for the project: he/she doesn't care how their programmers do their jobs as long as their programmers perform the task that meets the criterio given to them.

Likewise, the programmers know nothing about who the customer is and what he/she looks like or wants. The programmers don't really care who the customers are; all they care about is getting the task done.

Likewise, the customer knows nothing about who the programmers are and what they look like or where they're at or from. The customer only cares about is getting the website completed in the agreed timeframe.

And also, the programmers don't know how the manager got the instructions or whom he'd or she'd got it from. The programmers don't know what the heck the manager is doing either: the programmers just don't care what the manager is doing or how he/she is doing. It's not their job to know what the manager is doing.

Keep this seperation of concern in mind when you're dealing with MVC pattern.

As you can see, the three parties are completely independence of one another: in other words, they don't need to know what the other is doing or how the other is doing things. They all can do things in their own seperate unique ways without intertwine with one another.

Now imagine you're a large or small organization where you have lots of programmers working on all kinds of applications large or small and those programmers are spreading all over the world.

If all these programmers know MVC pattern, they can work on the same projects in different part of the world without knowing what the other programmers are doing on the same projects that they're working on.

This is the beauty of an MVC pattern where one group of developers working on the same project as the other group is located in far away from each other and they still can accomplish the same project without knowing what the other groups are doing.

In an MVC pattern, each party is seperate from one another and each party knows nothing about what the other party is doing. In an MVC pattern, each party doesn't need to know what the other party is doing as long as each party is doing its job in a unique/uniform way using MVC pattern.

Let's review: the customer requests to the manager telling the manager of what kind of application needs to be done; the manager, in turn, tells the programmers what tasks need to be done. That is all! Nothing else!

The customer doesn't know what the manager or the programmers are doing as long as the application gets done; while at the same time, the manager doesn't need to know what the programmers are doing as long as the task of getting the application done; and likewise, the programmers don't need to know what the customer looks like and how that customer's exact words to the manager--it doesn't matter.

When you approach to building an application in an MVC pattern, think of the above analogy -- it will help you a lot.

Here is a brief example on how to program in an MVC pattern.

In an abstract way, usually the index.php front page or a catalog page or an HTML form is the view 'V' rendering the page to the customers/users to allow customer/users to navigate throught the page looking to do/order things.

In the index.php front page or a catalog page or form, there should be some buttons or links for customers/users to navigate to the products or area of interest.

That's all the view 'V' is; nothing special: just HTML pages or forms that contain contents and buttons or links. Nothing else!

Now when a customer/user clicks on the button or link, it redirects the customer/user to another part of the website or sometimes to another remote site.

Now before it reaches another part of the website or another website remotely, it has to go through a controller 'C' (or a middle man or a manager in our case). It has to hand over the instructions to the manager to decide on what to do next. Logically, a manager will hand over the instructions to programmers to start performing the tasks.

Remember that the programmers are the model M who do all the heavy work.

In the case of a button or link, it contains a url to redirect to:

'http://www.example.com/index.php?site/controller'

Before I show you how to parse this url (above), I want to show you the server access command using .htaccess file. Put this file in the same directory as your index.php in the root directory of your project. This index.php file is typically called a starting script file.

This is the hand over the instructions to the programmers using routes.

Open up your text editor and create a file called .htaccess and put the following content inside it.

File: .htaccess

<?php
/** the .htaccess file starts with this line **/

RewriteEngine on

/** the above line says turn on the server **/

RewriteBase /

/** the above line says look for content after http://www.example.com/ **/
/** with '/' being the last '/' after '.com' **/


/** next line says allow all directories to go through **/

RewriteCond %{REQUEST_FILENAME} !-d

/** next line says allow all files to go through **/

RewriteCond %{REQUEST_FILENAME} !-f

/** next line is the rule pertaining to the url **/
/** this rule says look in an index.php as in http://www.example.com/index.php **/

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

/** continuing on above line: after the '?' is the querystring **/
/** this is like: ?site/controller/param1/param2/para3/... **/
/** so this string: url=$1 [L,QSA] is just for the server to read **/
/** the "L" stands for link, the Q for query, S for string, A for append **/

/** the below two lines are just more rules and server options **/
/** the first allow json file to go through and the second for options **/

RewriteRule \.(json)$ - [F]
Options -Indexes

/** you don't need to understand any of this content in this file **/
/** just use it "AS IS" but don't forget to remove my text description! **/

/** one important note: don't forget to remove the RewriteBase / entirely **/
/** if for some reason your website doesn't load! **/
/** I found that for some shared hosting it causes a problem! **/
/** so if it doesn't load, just remove the RewriteBase / entirely **/

/** for more on this topic, please Google the Web and there are **/
/** plenty of tutorials on the Internet! **/

?>

What the above .htaccess file does is allowing you to do like this on your url route:

<a href="http://www.example.com/site/controller/param1/param2/param3/...">link</a>

or just:

<a href="site/controller/param1/param2/param3/...">link</a>

For img:

<img src="image/picture_1.jpg">

Notice that for img tag, there is no route needed. The img tags are typically being used in the view to display images, and, therefore, routes are not needed. So you simply specify the src attribute that points to the directory of the image as you normally do in a non-MVC way.

For forms:

<form method="GET" action="http://www.example.com/site/controller/param1/param2/param3/..."></form>

Or just:

<form method="GET" action="site/controller/param1/param2/param3/..."></form>

For buttons:

<button type="button" onclick="http://www.example.com/site/controller/param1/param2/param3/..."></button>

Or just:

<button type="button" onclick="site/controller/param1/param2/param3/..."></button>

Basically, instead of having to write a complete route of

<a href="http://www.example.com/site/controller/param1/param2/param3/...">link</a>

on every link that you need, all you have to do is write just the querystring:

<a href="site/controller/param1/param2/param3/...">link</a>.

That's what the .htaccess file is for: allowing you to do a shortcut!

You will often route your form like this:

<form action="http://www.example.com/user/signup/param1/param2/param3/..." method="GET">

Or in a shortcut like this:

<form action="user/signup/param1/param2/param3/..." method="GET">

to route your user to the signup page. Notice that this is for a "GET" method. For a "POST" method see below.

The user part is the controller 'C' and the signup is the action. The rest are just "GET" method querystring.

If it is user/signup/id/guest/vip/ then user (the first part is always the controller 'C' and the second part signup is always the action, and the rest are extra GET parameters or querystring to send to the route.

In this case, there are three extra parameters that are being sent to the route: id, guest, and vip.

Please check out tutorials on the Internet to learn all these terms. The two most important terms are controller and action. Make sure you know what these two are and how to use them.

Hint: the controller is the class and the action is the method of the controller class. For example: user/signup.

<?php
// this is the controller
class User
    {
     // this is the action
     public function signup()
          {
           // method code
          }
    }
?>

Note that you can use "POST" method as well and it will route your route via a "POST" and not via a "GET". For example:

<?php
<form action="user/signup" method="post">
<input type="hidden" name="id" value="My_id_123">
<input type="hidden" name="guest" value="This is the guest content">
<input type="hidden" name="vip" value="This is the vip content">
<input type="submit" value="Submit">
</form>
?>

The above form sends the POST variables to the route: user/signup. The .htaccess file routes this request through a normal HTTP REQUEST channel using a POST method.

DO NOT add the querystring in the POST method like you do with a GET method. This is illegal: user/signup/id/guest/vip/.

Remember that you handle a POST request the usual way where you send it to; for example, in the above case, it sends to the controller or class 'User' to execute the method signup(). Somewhere in the class 'User', particularly in the method signup(), is where you handle the request by doing this: $_POST['id'], $_POST['guest'], $_POST['vip'].

The keyword here is 'somewhere' because as you know the HTTP REQUEST once it is sent, it is available everywhere. So for class 'User', it is available everywhere inside it. Self-explanatory!

Now we need to parse the route or querystring.

This is also part of the handover of the instructions to programmers.

<?php
class route
    {
     public $base = array();

     // now your main controller class will need to call
     // this method init()

     // you can do it inside your index.php starting file or from
     // inside your main application file, for example:
     // $route = new route();
     // $route->init();

     // for an example of a starting script file, see my other tutorial
     // called "how to autoload classes using SPL" and there is an
     // index.php file example shown at the very end of that tutorial!

     // see a lengthy explanation of the difference between an
     // index.php starting script file and the index.php/index.html
     // front page view [below]!

     public function init()
          {
           // class Base is the base controller class
           // I haven't written it yet! Maybe I won't!

           // did I mentioned that this is a very brief tutorial?
           // this will not be a complete tutorial! just to give you
           // an idea to move forward!

           // check out the Internet on topic of "MVC" base controller class!
           // basically, the "controller base class" is the main application
           // class that handles all the logic of the entire application.
           // see an example in my other tutorial called
           // "how to autoload classes using SPL"

           $this->base = new Base();

           //get the url fragments from the url
           $this->splitUrl();

           // you need to require/include the appropriate file directory
           require_once 'resource/dispatch/dispatcher.php';
           $dispatch = new dispatcher();

           // basically test to see if the url fragment in $x1 exists!
           // suppose that a visitor of your website types in the
           // url bar: example.com and the browser will try to
           // to load: http://www.example.com/index.php

           // now when it gets to splitUrl() it will return:
           // $x1 is null, $x2 is null, $x3 is null, etc.

           if (!isset($this->base->x1))
              {
               // so it comes here because $x1 is null!
               // it will load the default file index page!

               // don't be confused the default index page file with
               // the starting index.php file!

               // the two are completely different from one another!

               // the default index.php/index.html page is your index
               // front page typically can be found in the view, while
               // the starting script file index.php is the file to
               // jumpstart the application!

               // for an example of the default index.php/index.html
               // front page, see class dispatcher->init()
               // where the code that looks like this:

               // $this->base->render('index');

               // as you can see, the statement above renders the view's
               // index file: index.php/index.html in the 'view' folder!
               // that's what the statement below is doing!

               $dispatch->init();

               // for an example of the script's index.php starting file,
               // see my other tutorial called "how to autoload classes using SPL"
               // and at the very end of that tutorial,
               // there is a script file called index.php

               // this script index.php starting file should be at the root
               // of your application!

               // if you look in my other tutorial called 'getting started
               // programming for beginners', there is a section called
               // 'How to Install WAMP on Windows', particulary, step 10.
               // At the very end of that section where I show a
               // localhost containing a sample application folder called
               // "MyFirstWebsite"

               // inside that folder there are only three items: 'css' folder,
               // 'image' folder and the main starting script file 'index.php'
              }
           elseif (method_exists('dispatcher', $this->base->x1))
              {
               // now here, $x1 is NOT null!
               // this is the case where you can do in the view like this:

               //      <a href="about">About</a>
               //      <a href="affiliate">Afilliate</a>
               //      <a href="signup">Signup</a>
               //      <a href="login">Login</a>

               // this will load the controller page:

               //     dispatcher->about(), dispatcher->affiliate(),
               //     dispatcher->signup(), dispatcher->login()

               // now what happens if you put an index "home" link/route in
               // the view like the following?

               //          <a href="index">Home</a>

               // here, x1 = 'index' but there is no method called 'index'
               // in the 'dispatcher' class!

               // so it won't come here and it will fall into the default
               // condition below and displays the 'index' home page!

               // now what happens if you put a link/route in the view
               // like the following?

               //          <a href="user/signup">Signup</a>
               //          <form action="user/signup"></form>
               //          <a href="user/signup/id/guest/vip">Signup</a>
               //          <form action="user/signup/id/guest/vip"></form>

               // obviously, x1, x2, and x3, etc, are not null!
               // and therefore, it will still come here as well with:

               //          $x1 = 'user'
               //          $x2 = 'signup'
               //          $x3 = 'id'
               //          $x4 = 'guest'
               //          $x5 = 'vip'

               // in this case, only x1 and x2 are relevant and both will be
               // dispatched to the appropriate controller.
               // see class dispatcher->user() later on!

               $method = $this->base->x1;
               $dispatch->$method();
              }
           else
              {
               // this is the default condition!

               // if none of the conditions above are met,
               // it will load the default index.php page!

               // now what happens if you put a link/route in the view
               // like the following?

               //          <a href="index">Home<></a>
               //          <a href="unknown">Unkown Link</a>
               //          <a href="noroute">Not Sure</a>

               // all will come here because x1 = index, unknown, or noroute
               // and x2 is null!

               // so none of the conditions above are met,
               // so all three cases above will come here and
               // load the default index.php page!

               // note that for your "Home" link, you can use the domain name
               // as well (your domain), for example:

               //          <a href="http://www.example.com">Home</a>

               // I recommend that you use the domain name for your "Home" link
               // to avoid problems!

               // if you use index or other unknown/undefined method of the
               // controller (as shown above), it might give you an error saying:
               // "Can't load the page! Please check your url to make sure it is
               // the correct link!"

               // so using the domain name as your "Home" link ensures that it
               // will load the default index.php page every time! no errors!

               $dispatch->init();

               // now what happens if you put a form route in the view
               // like the following?

               //   <form action="unknown"></form>
               //   <input type="hidden" name="test" value="some test value">
               //   </form>

               // it will come here also because x1 = unknown, and x2 is null!
               // here is the problem: the browser is confused!

               // some browsers will load the default index.php and some browsers
               // don't know what to do and display an error: Can't load the page!

               // notice that we're talking about forms and not anchors!
               // so the browser is confused!

               // if it is an anchor it is probably okay and not confused!
               // to solve this problem, for forms use the correct route:
               // user/login, cart/addtocart, etc.

               // so be aware of these scenarios!
               // in other words, make sure you specify the correct route/link!
              }
          }

     // handling the incoming instructions from the view!

     // if the controller exists then call the controller
     // also store the properties in the main application object to
     // be used later: $this->base->x1

     public function splitUrl()
          {
           // if you look in the .htaccess file you'll see this:
           // RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

           // check if the url GET parameter is set
           // now the 'url' part is where we test for!
           if (isset($_GET['url']))
              {
               // load the url into url variable
               $url = $_GET['url'];

               // trim the url to remove slashes on right:
               // user/signup/id/guest/vip/

               // becomes:
               // user/signup/id/guest/vip

               $url = rtrim($url, '/');

               // break the url into fragments:

               // $url[0] = 'user', $url[1] = 'signup', $url[2] = 'id',
               // $url[3] = 'guest', $url[4] = 'vip'

               // what happens if a user types in the url bar like:
               //       http://www.example.com ?

               // splitUrl() will try to split the GET parameters and $url is null!
               // in other words, splitUrl() cannot split the GET parameter:
               // there is none!

               // and the foreach ($url) loop below will return null as well!
               // and therefore, x1, x2, x3 also will be null!

               // now what happens if you put a link/route like the following?

               //          <a href="about">About</a>
               //          <a href="affiliate">Afilliate</a>
               //          <a href="signup">Signup</a>
               //          <a href="login">Login</a>

               // it will split the url and $url contains an array of one element:

               //          $url[0] = 'about'
               //          $url[0] = 'affiliate'
               //          $url[0] = 'signup'
               //          $url[0] = 'login'

               // and therefore, x1 = 'about', 'affiliate', 'signup', 'login'
               // and x2 and x3 are null!

               $url = explode('/', $url);

               // load the url fragments as the object property variables
               // as x1, x2, x3 ....

               // in other words, set the main application's properties!
               // notice that in PHP, you can declare a property on the spot
               // and set it on the spot as well! very neat, huh?
               // this is exactly what happens in the method set() below!

               // you need to write a set($property, $value) in your main
               // application controller class (Base) as well as a get()
               // 
               // put the following two methods in your main base controller
               // public function set($property, $value)
               //      {
               //       $this->$property = $value;
               //      }
               // 
               // usage get():
               // 
               //    $base->get('x1'); 
               //
               // will return the controller, i.e.: user
               //
               // public function get($key)
               //      {
               //       if (isset($this->$key))
               //          {
               //           return $this->$key;
               //          }
               //       else
               //          {
               //           return null;
               //          }
               //      }

               foreach ($url as $key => $value)
                     {
                      $key++;

                      // this is basically setting class Base's properties
                      // so that we can use them later. see init() above!
                      // later, anywhere, we can do this:
                      // $base->x1, $base->x2, $base->x3

                      // this will become:
                      // x1 = $value, x2 = $value, x3 = $value ....
                      $this->base->set('x'.$key, $value);
                     }
              } // end if (isset($_GET['url']))
          } // end splitUrl()
    } // end class route
?>

Next is the dispatcher to dispatch the controller to the correct external controller.

Remember that there are two forms of controllers: internal controllers and external controllers.

In this case, the internal controllers are the class route and class dispatcher.

The external controllers are the controllers that actually doing the actual request to the models and as well as dictating to the views to display the views.

If you look in the method "user()" of the controller class "dispatcher" below, it creates an external controller by calling the createController() to create an external controller.

This is the manager who dictates to the programmers.

Remember that the manager only coordinates the job and doesn't do any heavy work at all! The heavy work is being done by the programmers.

As you can see below, the manager only asks the programmers to hand over the work by doing this: $base = new Base(). Now the manager knows nothing about what the programmers are doing inside class Base.

Now programmers all over the world can get to work on classes in their own seperate unique ways and none of them need to know what the others are doing. This is the seperation of concern of an MVC.

This example only shows one class or model; however, in a normal project large or small, there are lots of classes or models to be built and those classes or models can be given to groups of developers all over the world. And each group can work independently of one another without needing to know what the other groups are doing.

<?php
class dispatcher
    {
     public $base = array();

     // now class dispatcher's init function
     public function init()
          {
           // this method only contains two lines!

           $this->base = new Base();
           $this->base->render('index');

           // that's it!

           // the above call to render() tells the view to render
           // the actual file in the 'view' folder!

           // it is the controller telling the views to display the page
           // view!

           // the above call to render() will render the default front page:
           // resource/view/index.php or index.html

           // here is an example of render()

           // method render() renders the view.

           // this render() is incomplete as of now because I want you to
           // implement your own version of render to suite your objective!

           // how you implement your version of render() is up to you!
           // but I suggest that you implement it using only two arguments:

           //        $this->base->render($view, $template);

           // with $template, you might find it very useful to send in,
           // say, a theme, or even a model!
           // how you do it, it's up to you!

           // you can make improvements to this barebone render() to make it
           // more robust and powerful!

           // notice that render() below, $template is an array and is
           // initialized to null and you can call it like this:

           //        $this->base->render('index');
           //        $this->base->render('contact');
           //        $this->base->render('about');
           //        $this->base->render('affiliate');

           // below, the first argument is the page: index.php or contact.php
           // the second argument is the template or theme page or model or
           // whatever!

           // notice that you don't need more than two arguments!

           // put the following render() code in your main application
           // base class similar to the example class Base()

           // public function render($view, $template[] = null)
           //      {
           //       // setting the view template to default theme or whatever!
           //       // I won't show you the example and leave it for you
           //       // to implement in your own unique ways!

           //       // this "if" block needs more work to suite your objective!
           //       if ($template == null)
           //          {
           //           // set it to default theme or whatever!
           //           $template = 'default_theme';
           //          }

           //       // right here where you can branch out to different
           //       // views/files/themes

           //       // you can branch out to tidbits of snippets of code
           //       // views as well

           //       // right here, you can implement code that looks for
           //       // certain view and files that resides in a folder

           //       // it's a very good idea to implement code that can
           //       // handle views in its own folder.
           //       // that way you can put certain views in certain folders
           //       // for modularity purpose!

           //       // as stated earlier, how you implement your render()
           //       // is up to you!

           //       // but here is one possible way of doing it:

           //       // you implement your first argument that can receive
           //       // two items: view/index
           //       // with 'view' being the folder and index being the file!

           //       // you can call it like this:

           //       // $this->base->render('view/index');
           //       // $this->base->render('affiliate/index');
           //       // $this->base->render('about/index');
           //       // $this->base->render('profile/index');

           //       // OR

           //       // $this->base->render('catalog/index', $template);
           //       // $this->base->render('cart/index', $template);
           //       // $this->base->render('admin/index', $template);
           //       // $this->base->render('product/index', $template);

           //       // I won't show the latter case and leave it to you to do!

           //       // now let's illustrate the first case!
           //       // right here inside this render() you can do this:

           //       if (strpos($view, '/'))
           //          {
           //           $view = explode('/', $view);

           //           // now $view is an array of two elements: a folder and a file

           //           // $view[0] = 'view', $view[1] = 'index'
           //           // $view[0] = 'affiliate', $view[1] = 'index'
           //           // $view[0] = 'about', $view[1] = 'index'
           //           // $view[0] = 'profile', $view[1] = 'index'

           //           // from there, you can branch out to display the view from
           //           // its own folder!

           //           // as far as the second argument is concern, it is very
           //           // much can be anything: a theme or a model or anything!

           //           // right here where you refer to the view files
           //           // stored in the directory:

           //           $file = "resource/$view[0]/$view[1]" . '.php';

           //           if (file_exists($file))
           //              {
           //               require_once $file;
           //              }
           //           else
           //              {
           //               echo ("View file <b>resource/$view[0]/$view[1]</b>" .
           //               '.php not found');
           //              }
           //          }
           //       else
           //          {
           //           // you need to put all of your view files in a folder
           //           // called 'view' or whatever folder name you desire!

           //           $file = "resource/view/$view" . '.php';

           //           if (file_exists($file))
           //              {
           //               require_once $file;
           //              }
           //           else
           //              {
           //               echo ("View file <b>resource/view/$view</b>" .
           //               '.php not found');
           //              }
           //          }
           //      } // end render()
           //     *****    END OF RENDER()   *****

     // you'll have to create a file called about.php and put it
     // in the autoload directory!

     // see my other tutorial called "how to autoload classes using SPL"

     // do the same thing for the rest of these files:

     // this is the manager telling the programmers to handover the task!
     // maybe more appropriately the controller telling the view to
     // display the model or data!
     // the model is the the data to display: about.php

     // the route for this method is: <a href="about">About<>

     public function about()
          {
           $this->base->render('about');
          }

     // the controller telling the view to display the model or data!
     // the model is the the data to display: affiliate.php

     // the route for this method is: <a href="affiliate">Afilliate</a>

     public function affiliate()
          {
           $this->base->render('affiliate');
          }

     // the controller telling the view to display the model or data!
     // the model is the the data to display: signup.php

     // the route for this method is: <a href="signup">Signup</a>

     public function signup()
          {
           $this->base->render('signup');
          }

     // DIDO!

     // the route for this method is: <a href="login">Login</a>

     public function login()
          {
           $this->base->render('login');
          }

     // DIDO!

     // the route for this method is: <a href="profile">Profile</a>

     public function profile()
          {
           $this->base->render('profile');
          }

     // as you may know by the look of this controller class 'dispatcher',
     // it is very cluttered if you have lots of conttollers/actions!
     // it will make this class very hard to navigate and debug!

     // a better solution is to do what I'm attempting to do below,
     // and that is, create a controller method in your base/main
     // application class similar to this example base class Base()!

     // inside this main base class, you can create a controller method.

     // this is my attempt to make this MVC application more robust and
     // powerful by creating a controller instance and then call that
     // external controller from here to execute that external controller!

     // when a view sends a controller/action such as user/login
     // it comes here and it looks for an external controller/action to
     // route to by calling the createController() method below!

     // remember that this class dispatcher is a controller but this
     // controller can have other external controllers as well!
     // sort of manager of managers: head manager having middle managers!

     // I call them inner controllers and external controllers!

     // put this method in your main application base class similar
     // to Base()

     // public function createController($controller)
     //      {
     //       // here, you put all of your controller files in folder:
     //       // controller
     //
     //       // this will load a controller class file like these:
     //
     //       //               controller/UserController.php
     //       //               controller/AdminController.php
     //       //               controller/CartController.php
     //       //               controller/MediaController.php
     //
     //       // make sure to name your external controller files accordingly!
     //       // e.g., UserController.php, AdminController.php, etc.
     //
     //       // the reason that you append the word 'Controller' to your
     //       // external controller files is to differentiate them from
     //       // other classes, say, 'model' and 'view'!
     //
     //       // then in the external class definition, you can name your
     //       // external controller classes accordingly, e.g.,
     //
     //       // UserController, AdminController, CartController, etc.
     //
     //       // you can convert the first letter in $controller to uppercase
     //       // using function ucfirst()
     //
     //       // ucfirst($controller)
     //
     //       $file = "controller/$controller" . 'Controller' . '.php';
     //       if (file_exists($file))
     //          {
     //           require_once($file);
     //           $controllerObj = new $controller();
     //
     //           // return an instance of the controller class back to
     //           // the caller!
     //           // see an example controller class user below!
     //           return $controllerObj;
     //           }
     //        else
     //           {
     //            echo ("$controller" . 'Controller not found.');
     //           }
     //     *****    end of createController()   *****

     // right here, you group all the action methods of class 'User'
     // to call to: User->login, User->logout, User->profile, etc!
     // don't mix up with function user() below with controller class
     // 'User' later as in: createController('user')

     // the route for this method user() could be something like this:

     // <a href="user/login/id/guest/vip">Login</a>
     // or just:
     // <a href="user/login">Login</a>

     // <a href="user/logout/id/guest/vip">Logout</a>
     // or just:
     // <a href="user/logout">Logout</a>

     // <a href="user/profile/id/guest/vip">Profile</a>
     // <a href="user/admin_login/id/guest/vip">Admin Login</a>
     // <a href="user/admin_logout/id/guest/vip">Admin Logout</a>
     // <a href="user/admin_singup/id/guest/vip">Admin Signup</a>
     // <a href="user/forgot/id/guest/vip">Forgot Password<></a>
     // <a href="user/usernamecheck/id/guest/vip">Check Username</a>
     // <a href="user/emailcheck/id/guest/vip">Check Email</a>

     // and they will come here!

     public function user()
          {
           $x2 = $this->base->get('x2');
           switch ($x2)
                {
                 // the manager is asking the programmers to
                 // handover the tasks!

                 case 'login':
                 case 'logout':
                 case 'profile':
                 case 'admin_login':
                 case 'admin_logout':
                 case 'admin_singup':
                 case 'forgot':
                 case 'usernamecheck':
                 case 'emailcheck':

                 // right here, if any of the above case is met,
                 // it will come here to look for a specific
                 // controller action: $x2

                 // basically, $x2 is the action or controller
                 // method: login()

                 // we need to specify the external controller class as
                 // 'user' and it will route to that controller looking
                 // for an action method to execute!

                 // creating an external controller: 'user'
                 $this->base->createController('user')->$x2();

                 // you can pass the controller as a variable as well:
                 // $this->base->createController($x1)->$x2();
                 break;
                 default:
                      $this->init();
                }

           // as you can see, this is much more robust and powerful as it
           // allows you to route to each controller class and to look for
           // specific actions in that class!

           // you can use this example method user() to do other external
           // controller/action to make your MVC application more robust!

           // notice that you can group these actions: about(), affiliate(),
           //  signup(), login(), profile() in a class of their own similar
           // to the class 'User' and thus makes it more robust and powerful
           // and less cluttered!
          }
    } // end class dispatcher

// as you can see, createController('external_controller_class') creates
// an instance of the external controller class!

// now you need to create those external controller classes!

// here is an example of the controller class User!

// this is the controller 'user'

// or if you want to differentiate your controller classes from
// other classes, you can append the word 'Controller' to the class
// name: 'UserController'

// see createController() example above for more detail!

// class User
//     {
//      // public $base;

//      // $this->base = new Base();

//      // this is the action 'login'
//      public function login()
//           {
//            // remember that this is the controller/manager
//            // and the manager doesn't do any heavy work!
//            // so the manager usually asks the workers to
//            // do the actual heavy work!

//            // so you should never have to do any heavy programming
//            // in any of your "external" controllers!

//            // the controller should always asks the model to return
//            // true or false whether the task is successfully
//            // or not! that's all!

//            // an example of that is the creation of class Base instance
//            // above! as you can see, the controller/manager does
//            // absolutely nothing in the form of heavy work!

//            // the login credential: username and password
//            // is available at the view via: HTTP REQUEST!

//            // send it to the view: a login form!
//            $this->base-render('login');
//           }

//      // this is the action "profile"
//      public function Profile()
//           {
//            // remember that this is the controller/manager
//            // and the manager doesn't do any heavy work!
//            // so the manager usually asks the workers to
//            // do the actual heavy work!

//            // so you should never have to do any heavy programming
//            // in any of your controllers!

//            // the controller should always asks the model to return
//            // true or false whether the task is successfully
//            // or not! that's all!

//            // an example of that is the creation of class Base instance
//            // above! as you can see, the controller/manager does
//            // absolutely nothing in the form of heavy work!

//            // send it to the view to display the profile!
//            $this->base-render('profile');
//           }

// this is the controlller

// if you want to differentiate your controller classes from
// other classes, you can append the word 'Controller' to the class
// name: 'UserController'

// see createController() example above for more detail!

// class SomeOtherController
//     {
//      public $base = array();

//      $this->base = new Base();

//      // this is the action "someaction"
//      public function SomeAction()
//           {
//            // remember that this is the controller/manager
//            // and the manager doesn't do any heavy work!
//            // so the manager usually asks the workers to
//            // do the actual heavy work!

//            // so you should never have to do any heavy programming
//            // in any of your controllers!

//            // the controller should always asks the model to return
//            // true or false whether the task is successfully
//            // or not! that's all!

//            // an example of that is the creation of class Base instance
//            // above! as you can see, the controller/manager does
//            // absolutely nothing in the form of heavy work!

//            // send it to the view to display the someview!
//            $this->base-render('someview');
//           }
    } // end class dispatcher
?>

Notice that the manager does very little! All of the heavy work load is being done by the programmers.

Keep this analogy in mind as you work through the MVC pattern. There should not be any heavy work being done by the controllers. The controllers only need to know true or false. That's all! Nothing else!

For example, if you're programming a registration or login application, the model or models need to return only true or false if a user is successfully registered or logged in. Likewise, with other models, they need to return only true or false to the controller and nothing else.

For example, if a model is retrieving a bunch of products to be used in a catalog display in a view, the model can return true if the products are successfully retrieved from the database or false otherwise. For example:

<?php
/**
 * retrieve the products from the database
 */
class Product
    {
     // constructor
     public function __construct()
          {
           // constructor code logic);
          }

     // get the product
     public function getProduct()
          {
           // code logic
           // query the database: SELECT * FROM Product
           // return the product to the controller as an array!
          }
    }
?>

In getProduct(), you need to retrieve the products from the database and return the products accordingly so that in the controller, you can just test to see if it returns any product or null. True or false!

In the controller, all it needs to be done is instantiating the model: $product = new Product().

$model = $product->getProduct().

Now the controller or manager can handover the product to the view.

You can send it to the view via a render() method: $this->base->render('catalog', ['model' => $model]).

Remember that the second argument of render() is an array, and, therefore, you can send a model containing an array.

The trick is to test for the second argument for an array element: 'model' inside your render(). How you implement the second argument logic is up to you.

However, there is an easier way to send models to the view:

$this->base->set('model', $model).

Now the above line sets the property called 'model' to your base controller class similar to class Base() in this example.

Now using set() above, the controller or manager can handover the product to the view: render('catalog').

Notice that it is much simpler and there is no model attached to render().

Now inside the catalog view, you can retrieve that property like this: $catalog = $this->base->get('model').

Display the catalog. For example, inside the view 'catalog.php':

foreach ($catalog as $key => $value)

$key should be a product id and $value should be an array holding the product object: id, name, price, description, image, etc.

How you implement your view's render() is up to you. You can make improvement to the barebone render() code example shown earlier to make it more robust, like handling multiple themes and files.

Inside the barebone render() you can make it more robust and powerful by branching out to display snippets of views like sidebars flash display, ad flash display, and other content displays. See earlier code example for guidance.

Note that it is a good idea to specify the second argument of render() as an array: render($view, $template = array())

Please use the very popular shorthand array: render($view, $template = []).

This way, you can send all kinds of content to the view!

Note that you don't need more than two arguments in render() as the second argument handles all kinds of content to be sent to the view.

You can specify the second argument as an optional argument as well by doing this: render($view, $template[] = null).

By doing that you can send only the view that are simple views like about, contact, profile, etc.: render($view).

The Models: Classes

As stated above, there should not be any heavy work being done by the controllers. All of the heavy work load should be done by the models.

The models should be autoloaded using SPL autoload and are grouped in their own folders. Likewise, for the views and controllers, they should be grouped in their own folders and autoloading them accordingly. See my other tutorials called "how to autoload classes using SPL."

To learn more about MVC pattern, please check out the Internet by Googling the term MVC or Model View Controller.

There you have it: a very brief but useful introduction to MVC pattern. You should be able to use this MVC pattern tutorial and build your very own sophisticated applications--large or small. From here, the possibilities are endless!

Have fun programming and don't forget to thank me later!


PHP Visibility or access control: public, protected, and private

What is the difference between public, protected, and private ?

public, protected, and private are visibility clauses (similar to static and final). A visibility clause is a term used to describe the access control in certain part of the code. It's like a key to a toolbox where you are allowed to use certain tools for certain projects only if you have the key to open it. It is restricted to use certain tools. So you can't just go grab the tools and use freely; you have to have certain keys to open the toolbox and use the tools.

In programming, we have visisibility clauses or visibility controls to allow you to restrict certain part of the code to be accessible to certain programs.

Visisibility clauses or visibility controls allow certain part of code to be protected from outside abuses. Visisibility clause or access control is about controlling visibility of the methods and variables from outside classes usage. The visibility of the code elements are determined by their access control specifications or clauses: public, protected, and private.

Note: the term visisibility clause or access control mean the same thing and both are being used interchangibly.

To "protect" a method or variable from unauthorize references, you use the three levels of access control visibility: public, protected, and private.

A class is like an island onto itself where only people on the island can get access to the resources residing on that island. Because of this inaccessibility that a method of distinguishing who is allowed to get on and who is not allowed to get on -- and what level of restrictions certain methods and variables are placed on -- was developed.

The three-level of restrictions was developed to allow access control of the methods and variables.

Note: Visibility access control only concern with methods and variables and nothing else. Variables sometimes referred to as property variables or just plainly properties. So keep this in mind as you go through the descriptons:

  • Class methods and variables declared as public can be accessed everywhere.

  • Class methods and variables declared as protected can be accessed only within the class itself and by classes derived from that class.

  • Class methods and variables declared as private may only be accessed by the class that defines the methods and variables. In other words, ONLY the class that defines the private methods and variables can access these private methods and variables [that they defined themselves].

    All other classes cannot access these private methods and variables [of another class or classes]. They can ONLY access their own private methods and variables.


  • Class methods and variables declared without any explicit visibility keyword are defined as public.

Before we get into the main visibility access control: public, protected, and private, let's get this one nagging issue out of the way that seems to get a lot of people confused, and that is, the use of keyword var. For example:

<?php
class MyClass
    {
     /** declaring MyClass' properties: **/

     /**
      * as you can see below, we declare a property called $make as 'public'
      * using the keyword 'var'.
      * this is the same as declaring: public $make
      */

     var $make; // declaring a property as 'public'

     // for non-public properties, you use the appropriate clause, i.e., protected.
     protected $model;

     // for non-public properties, you use the appropriate clause, i.e., private.
     private $color;
    }
?>

The keyword var was the original design to signify the property as a public variable. So instead of having to specifically declaring a property using the keyword public, all we had to do was using the keyword var followed by the variable name and we had a public property variable. That was in the old days!

Then the folks at PHP decided to get rid of the old legacy mistake and instituted the proper way of doing things by replacing the keyword var with the keyword public starting in PHP 5.0. Then an uproar erupted and created a lot of confusion. It lasted for a couple of versions until it was too much of a headache to bear and they decided to put back the old legacy style by re-instituting the keyword var to its original style starting in PHP 5.3.

Since version 5.3 and onward, you can actually use either of the two keywords and they will all work just fine. However, they really stress/encourage all programmers to use keyword public and discourage the use of keyword var.

Visibility Access Control: Public, Protected, and Private

Let's see how to use the visibility access control: public, protected, and private. For example:

<?php
/**
 * declaring class Vehicle's properties only -- no methods
 */
class Vehicle
    {
     // declaring class Vehicle's properties:
     public $make; // declaring a property as 'public'
     protected $model; // declaring a property as 'protected'
     private $color; // declaring a property as 'private'
    }
?>

Now to see the effect of the visibility clauses in action, consider this:

<?php
/**
 * now we're creating another class outside of class Vehicle.
 * this class will try to get through class Vehicle's visibility control.
 * let's see if this class can get through class Vehicle's visibility control.
 */
class Ford
    {
     // creating an instance of class Vehicle:
     $obj = new Vehicle();

     // now try to get through class Vehicle's visibility control.

     /**
      * this reference is fine because the property is declared as
      * 'public'. so class Vehicle allows class Ford to use its property.
      */
     $obj->make = 'Ford';

     /**
      * this reference will cause a 'fatal error' because the property is declared as
      * 'protected'. so class Vehicle didn't allow class Ford to use its property.
      */
     $obj->model = 'F150';

     /**
      * this reference will cause a 'fatal error' because the property is declared as
      * 'private'. so class Vehicle didn't allow class Ford to use its property.
      */
     $obj->color = 'grey';
    }
?>

As you can see, declaring methods and properties as protected and private restricts outside classes like Ford from using its properties.

Now let's take a look at the same class Vehicle definition again but this time with methods and property variables. For example:

<?php
/**
 * now we're adding methods to class Vehicle.
 */
class Vehicle
    {
     // declaring class Vehicle's properties:
     public $make; // declaring a property as 'public'
     protected $model; // declaring a property as 'protected'
     private $color; // declaring a property as 'private'

     /**
      * declaring class Vehicle's method as 'public'
      * notice that declaring a method without the visibility clause has
      * the same effect as 'public'. so the 'public' clause can be omitted!
      */
     public function setMake($make)
          {
           // assigning a value to class Vehicle's property
           $this->make = $make;
          }

     // declaring class Vehicle's method as 'protected'
     protected function setModel($model)
             {
              // assigning a value to class Vehicle's property
              $this->model = $model;
             }

     // again, declaring class Vehicle's method as 'private'
     private function setColor($color)
           {
            // assigning a value to class Vehicle's property
            $this->color = $color;
           }
    }
?>

Now to see the effect of the visibility clauses in action, consider this:

<?php
/**
 * now we're creating another class outside of class Vehicle.
 * this class will try to get through class Vehicle's visibility control.
 * let's see if this class can get through class Vehicle's visibility control.
 */
class Audi
    {
     // creating an instance of class Vehicle:
     $obj = new Vehicle();

     // now try to get through class Vehicle's visibility control.

     /**
      * this reference is fine because method setMake() was declared as
      * 'public'. so class Vehicle allows class Audi to use its method.
      */
     $obj->setMake('Audi');

     /**
      * this reference will cause a 'fatal error' because setModel() was declared as
      * 'protected'. so class Vehicle didn't allow class Audi to use its method.
      */
     $obj->setModel('A6');

     /**
      * this reference will cause a 'fatal error' because setColor() was declared as
      * 'private'. likewise, class Vehicle didn't allow class Audi to use its method.
      */
     $obj->setColor('grey');
    }
?>

As you can see, declaring methods and properties as protected and private can be accessed only from within the class that those methods and properties are defined.

Inheritance and Protected Visibility Access

In the previous description, in the beginning introductory description, it stated that 'protected properties or methods can be accessed within the class and by classes derived from that class'. What does that mean?

Let's take a look at the same class definition Vehicle but this time we will extend this Vehicle class further and see if child classes can get access to class Vehicle's visibility control:

<?php
class Vehicle
    {
     /**
      * declaring class Vehicle's properties as private:
      * notice that these two 'private' properties can be accessed only from inside
      * this Vehicle class. classes that extends from Vehicle cannot access these
      * two private properties.
      */

     private $price;
     private $tax;

     /**
      * declaring class Vehicle's constructor as 'public'
      * notice that declaring a method/constructor without the visibility clause
      * has the same effect as 'public'. so the 'public' clause can be omitted!
      */

     public function __construct($price, $taxRate)
          {
           /**
            * assigning values to class Vehicle's properties
            * 'private' properties can be accessed only from inside this Vehicle class
            */
           $this->price = $price;
           $this->tax = $taxRate;
          }

     /**
      * if calculateTax() was declared as 'private' no child class can access this
      * private method. the only method that can access this private method is from inside
      * the constructor using $this, for example: $this->calculateTax()
      *
      * let's be clear about this: ONLY if calculateTax() is declared as 'private'
      *
      * let's clarify that statement earlier a little bit:
      * 'the only method that can access this private method is from inside the constructor'
      *
      * that statement is only true if this Vehicle class has only the constructor method as
      * it stands right now.
      * if there are more methods to be had, regardless of their visibility clause,
      * then they all can access to these private properties as well as other private methods
      * of class Vehicle. so 'private' means ONLY within the class itself and not outside of
      * the class. this means that any method within the class can access 'private' properties
      * and methods declared within the class.
      * so make note of that!
      *
      * this means that no other class or classes even child class or classes of Vehicle can
      * get access to class Vehicle's private properties and methods.
      *
      * however, calculateTax() is declared as "protected" and therefore child classes of
      * Vehicle can get access to calculateTax() just fine!
      *
      * did you remember a phrase that goes like this [?]:
      * 'protected can be accessed only within the class itself and by classes derived from
      * that class'.
      *
      * this is exactly what that phrase means!
      *
      * here is the 'protected' method calculateTax()
      */

     protected function calculateTax()
             {
              /**
               * now since this method is declared as 'protected' child classes that extend
               * from this parent class Vehicle can get access to this 'protected' method.
               * no other classes can get access to this 'protected' method.
               */

              // getting a tax
              $tax = $this->$price x $this->$taxRate;
              return $tax;
             }
    }
?>

Now to see the effect of the protected or private visibility clause in action, consider this:

<?php
class Ford extends Vehicle
    {
     public function getTax()
          {
           // getting a tax from parent class Vehicle

           // calling a protected method, is it legal?
           // see below and an explanation later as well!
           $tax = $this->calculateTax();
           return $tax;

           /**
            * the 'protected' rule: child classes that extend from a parent class with
            * methods declared as 'protected' can get access to those 'protected methods.
            * no other classes can get access to those 'protected' methods.
            */
          }
    }
?>

Now to see the effect of the visibility clauses in action in child class Ford, consider this:

<?php
/**
 * now we're creating another class Audi outside of class Vehicle and Ford.
 * this class Audi will try to get through Vehicle's and Ford's visibility controls.
 * let's see if Audi can get through class Vehicle's and Ford's visibility controls.
 */
class Audi
    {
     // creating an instance of class Ford which extends Vehicle:
     $obj = new Ford('25000', '0.07');

     /** now try to get through class Ford's and Vehicle's visibility controls. **/

     /**
      * calling $obj->getTax() is OK because Ford's method getTax() was declared as
      * 'public'. so class Ford allows class Audi to use its method getTax().
      * now, in turn, getTax() calls calculateTax() (which is declared as 'protected') from
      * within the derived class Ford.
      *
      * a public method getTax() calls a protected method calculateTax()!
      *
      * is it legal for a public method to call a protected method?
      *
      * did you remember a phrase that goes like this [?]:
      * 'protected can be accessed only within the class itself and by classes derived from
      * that class'.
      *
      * '.... by classes derived from that class' means Ford derived from Vehicle.
      *
      * getTax() calls calculateTax() from inside class Ford.
      * class Ford is a derived class from Vehicle.
      *
      * as you can see, it is OK for a public method to call a protected method from
      * inside the derived class, in this case, Ford.
      */

     $obj->getTax();   // calling $obj->getTax() is OK because getTax() is 'public'
    }
?>

Summary

Let's re-cap what the three visibility control are:

  • public just the word implies, it is open to the public and anybody can get access to these public methods and properties.

  • protected just like the word implies, it is protected within the family and relative circle, and others outside of the family and relative circle cannot get accessed to the protected methods and properties. This means that child class (or classes) methods and properties declaring as public can get access to parent class methods and properties declared as protected.

  • private just like the word implies, it is a private matter/affair and it is not open to the public or to their own descendant classes either. This is very strict even their own relatives and descendants can't even get accessed to methods and properties of a private class.

    methods and properties inside a private class can only be accessed from inside that private class by their own member methods and properties. Child class or classes of the private class cannot get accessed to their own parent's methods and properties. That is very harsh!

So the key to remembering these three visibility controls is that, just think of them in term of real life examples like family and relatives and strangers and associate each scenario accordingly.

Another point is, to memorize protected first and leave the other two alone.

In other words, don't try to memorize the other two and only try to memorize protected very good. That way, you don't get them mixed up so easily.

Just think that protected is a protection within the family and relative, and descendants cycle and anybody outside of the cycle cannot get accessed to protected methods and properties.


A Brief Introduction to Overriding Inherited Methods


What is overriding inherited methods?

Parent methods (such as constructors) can be overridden by child classes. To override parent methods, just redefine the parent methods (using the same name) in the child classes. For example, in class Vehicle shown earlier in the previous section, it has a constructor with two argument parameters: __construct($price, $taxRate) and a protected method called calculateTax().

You can define a child class called Toyota that overrides and extends class Vehicle to contain more constructor's argument parameters. Let's create a child class that has a constructor with two additional argument parameters in addition to the two argument parameters that parent class Vehicle already has. For example:

<?php
class Toyota extends Vehicle
    {
     // declaring class Toyota's properties as private:

     private $rebate;
     private $carbonTax;

     // declaring class Toyota's constructor with two additional parameters

     public function __construct($price, $taxRate, $rebate, $carbonTax)
          {
           /**
            * assigning values to class Vehicle's properties
            * $this refers to class Vehicle's properties
            */
           $this->price = $price;
           $this->tax = $taxRate;

           /**
            * assigning values to class Toyota's properties
            * $this refers to class Toyota's properties
            */
           $this->rebate = $rebate;
           $this->carbonTax = $carbonTax;
          }

     protected function calculateTax()
             {
              // getting a tax
              $tax = $this->$price x $this->$taxRate + $this->carbonTax - $this->rebate;
              return $tax;
             }
    }
?>

As you can see, the __construct() and calculateTax() methods in the child class (Toyota) override the __construct() and calculateTax() methods in the parent class (Vehicle).

Now to see the effect of the override methods in action in child class Toyota, consider this:

<?php
/**
 * now we're creating another class Ford outside of class Vehicle and Toyota.
 */
class Ford
    {
     // creating an instance of class Toyota which has four parameters:
     $obj = new Toyota('25000', '0.07', '5000', '2500');

     // call the newly inherited Toyota's method calculateTax()

     $obj->calculateTax();
    }
?>


A Brief Introduction to Machine Learning/Neural Network


This tutorial is being worked on and improvement and fine-tuning and simplifying are forthcoming. Stay tuned!!!

Neural networks are parallel computing programs or models, which are basically an attempt to make a computer model of the brain. The main objective is to develop a system to perform various computational tasks faster than the traditional systems. This tutorial covers the basic concept and terminologies involved in Artificial Neural Network.

Biological Neuron

A nerve cell (neuron) is a special biological cell that processes information. According to an estimation, there are huge number of neurons, approximately 1011 with numerous interconnections, approximately 1015.



As shown in the above diagram, a typical neuron consists of the following four parts and with the help of Wikipedia I can briefly explain its working.

Note that you don't need to memorize the terms (or names) presented above or the following four terms below, either. It's for illustration purpose only:

  • Dendrites - Are brain cells that receive and response signals from/to other parts of the brain cells. They are tree-like branches, responsible for receiving the information from other neurons it is connected to. In other sense, we can say that they are like the ears of neuron.


  • Soma - It is the cell body of the neuron and is responsible for processing of information received from dendrites.


  • Axon - It is just like a cable through which neurons send the information.


  • Synapses - It is the connection between the axon and other neuron dendrites.

So the combined brain cells shown in the above diagram is called neural network. It's how brain functions. We use a form of machine learning called neural network to mimick how human brain works. I should say we try to mimick how human brain works. We will never be able to replicate how human brain works using machine learning.

Just like human brain receives and responses to signals from other cells within the brain, in machine learning, we mimick that feature by providing signals to the computer program to process the signals. To do that, we fetch in information through the input channels so that the computer can use the input to further process the information. See the diagram below.

Note that up to this point you don't need to understand any of the content presented above; it's for illustration purpose only and you don't need to understand it, nor do you need to memorize it either. In other words, you don't need to memorize the terms presented above. It's for illustration purpose only.

However, starting from the diagram below, you'll need to understand the context of the illustration and its meaning.



As you can see, this is a very simple model to illustrate how neural network works. Starting from the left side neuron is where information is fetched in (or bring in or input in) to be processed. Next, the middle neuron (ellipse x 180) is where all the first layer of processing takes place. In this layer, we have only one input , and, therefore, there is only one processing task to do. And that is, to multiply the input obtained from the circle on the left by an arbitrarily value called weight. Notice that I put x 180 in the ellipse diagram to show that 180 is my weight to be multiplied by the input. I will come back to discuss weight in a little bit later.

So if the input is 2, 2 x 180 = 360.
If the input is 5, 5 x 180 = 900.
If the input is 10, 10 x 180 = 1800.

Simple enough?

Now about the weight: Just remember this:

Every input can contain a weight - but it doesn't have to.

Now that we have the result we can pass it to the output which is denoted as a circle with letter 'y' under it on the right side. And that is the final result.

Now a little more sophisticated neuron. This time we have three input neurons, labeled x1, x2, x3, and everything else stays the same. [Disregard the letter 'b' in the middle layer. It's my typo]:



We need to do the same thing as we did with our simple neuron, and that is, to multiply the input obtained from each input value on the left by an arbitrarily weight value that we can assign. Again, I'll come back to this weight in a little bit.

So the idea is that you take each input and multiply it by its weight. You do this for all the inputs and then once you got all the results from the multiplications, you add them all up to get the final result. This is called the weighted sum.

Now assuming we assign a weight value of 100 for the first input, x1, a weight value of 20 for the second input, x2, and a weight value of 50 for the third input, x3, we obtain the multiplication results as follow:

So if the first input, x1, is 2, 2 x 100 = 200.
If the second input, x2, is 5, 5 x 20 = 100.
If the third input, x3, is 10, 10 x 50 = 500.

Now we have three results, but we can't have three results; so we need to normalize it by what is called the weighted sum. So add all the neurons together to get the result so that we can pass it on to the output. So 200 + 100 + 500 = 800. So the output y = 800. That is it!

Simple enough?

We're moving right along. This time, we have three input neurons, four hidden neurons in hidden layer 1 , four hidden neurons in hidden layer 2, and the usual output layer which is just one output neuron. Note that the output neuron is always one neuron and cannot have more than one, but the input and the hidden layers can have limitless neurons.



If you look at the diagram, you'll see three input neurons and the next layer, hidden layer 1, has four neurons. To get the result for each of the four neurons in hidden layer 1, we need to do a weighted sum for all three inputs, x1, x2, x3. For example:

I'm going to label each input using subscript like so, top to bottom: x1, x2, x3.

I'm going to label each weight using subscript like so, top to bottom: w1, w2, w3, w4.

Now we have three inputs, x1, x2, x3, and also we have four weights, w1, w2, w3, w4.

We can now do the multiplications and the weighted sums together in one step for each of the four neurons in the hidden layer 1:

But first, let's suppose that we have the three inputs, x1 = 2, x2 = 5, x3 = 10, and also we have the four weights, w1 = 100, w2 = 20, w3 = 8, w4 = 30.

We can do a weighted sum for the top neuron in hidden layer 1 like this: x1 * w1 + x2 * w1 + x3 * w1.

Do you see how a weighted sum works?

Each input has to be multiplied by each weight for each neuron. See the arrows pointing from each input to each neuron. Follow the arrows in the diagram and you'll be okay.

I'm going to re-use the already drawn up diagram that was intended for another use in a later illustration. Here it is:



If you look at the diagram above, you'll see that each input (labelled as X1 or X2) has a weight (labelled as W1 or W2, respectively.) This is how they usually label each neuron and its weight and you should follow the same technique as shown here.

I've seen some people put each weight right inside the hidden layer, which is easier to visualize. If you look at the previous diagram that has three inputs and four neurons in hidden layer 1 and 2, you'll see that it makes a lot of sense to put the weight inside the hidden layer neurons.

But technically, inside a hidden layer is where you calculate activation function and may not be a good place to put the weight there. Not only that, inside a hidden layer is where you put the result from the multiplication of the input with its weight. And that result serves as an input for that hidden layer as well. So definitely it's not a good place to put the weight there.

If it is easier to visualize it, then it's okay to put your weight there. There is nothing wrong with that! But I recommend follow the traditional way of doing so that you don't stray too far away from the usual way of doing.

For the previous diagram that has three inputs and four neurons in hidden layer 1 and 2, you can just put the weight right on each line that leads to the arrow pointing to the neuron in the hidden layer 1 or 2.

Notice that in the previous diagram that has three inputs and four neurons in hidden layer 1 and 2, each input has four lines connecting from each input and leading to each neuron in hidden layer 1 and 2. Those four lines are where you put the weights on [right on each line]: just label it, top to bottom, like so: w1, w2, w3, w4.

If you look at the previous diagram that has three inputs and four neurons in hidden layer 1 and 2, I just told you to just put each weight on each line for all four neurons [using proper subscripts], which means that for hidden layer 1 and 2, those weights: w1, w2, w3, w4 stay the same for both hidden layer 1 and 2, and that is not correct.

Factually, each hidden layer has its own weights, so by me telling you to label your weights containing the same subscripts is factual incorrect. In other words, telling you to label weights for hidden layer 1 as w1, w2, w3, w4 and [also] hidden layer 2 as w1, w2, w3, w4 is incorrect. All hidden layers have different sets of weight.

But my intention is to help you understand the concept visually [this early in the stage] even thought technically it is incorrect. Later on, you'll learn how to label your neurons (including their weights) properly using subscripts. For now, just label it as shown above so that you can visualize it clearly.

Getting back to the weighted sum: After the multiplications, add them all up.

Now plug the values into the equation and we get 1700: 2 * 100 + 5 * 100 + 10 * 100 = 1700.

A weighted sum for the second neuron from the top in hidden layer 1 like this: x1 * w2 + x2 * w2 + x3 * w2.

Notice that each input, in this case, each x1 or each x2 or each x3 has to be multiplied by a weight, in this case, w2. Follow the arrows in the diagram for all the inputs and continue this same process for all other neurons in the hidden layers as well.

Pluging the values into the equation and we get 340: 2 * 20 + 5 * 20 + 10 * 20 = 340.

A weighted sum for the third neuron from the top in hidden layer 1 like this: x1 * w3 + x2 * w3 + x3 * w3.

Pluging the values into the equation and we get 136: 2 * 8 + 5 * 8 + 10 * 8 = 136.

A weighted sum for the fourth neuron from the top (or the bottom neuron) in hidden layer 1 like this: x1 * w4 + x2 * w4 + x3 * w4.

Pluging the values into the equation and we get 510: 2 * 30 + 5 * 30 + 10 * 30 = 510.

Now we have the results for each of the four neurons in hidden layer 1. These four results serve as input neurons for each of the neurons in hidden layer 2. This is called feed forward or forward propagation -- a process of passing the result from one layer to the next. More on feed forward or forward propagation later.

Let's use these four results as input neurons for hidden layer 2, x1 = 1700, x2 = 340, x3 = 136, x4 = 510, and also we have the four new assinged weights, w1 = 3, w2 = 1, w3 = 4, w4 = 6 for each of the four neurons in hidden layer 2.

We can now do a weighted sum for the top neuron in hidden layer 2 like this: x1 * w1 + x2 * w1 + x3 * w1 + x4 * w1.

Notice that now we have four inputs in this hidden layer, hidden layer 2, since the four results we've got from hidden layer 1 serve (or feed) as input neurons for hidden layer 2.

Pluging the values into the equation and we get 8,058: 1700 * 3 + 340 * 3 + 136 * 3 + 510 * 3 = 8,058.

A weighted sum for the second neuron from the top in hidden layer 2 like this: x1 * w2 + x2 * w2 + x3 * w2 + x4 * w2.

Pluging the values into the equation and we get 2,686: 1700 * 1 + 340 * 1 + 136 * 1 + 510 * 1 = 2,686.

A weighted sum for the third neuron from the top in hidden layer 2 like this: x1 * w3 + x2 * w3 + x3 * w3 + x4 * w3.

Pluging the values into the equation and we get 10,744: 1700 * 4 + 340 * 4 + 136 * 4 + 510 * 4 = 10,744.

A weighted sum for the fourth neuron from the top (or the bottom neuron) in hidden layer 2 like this: x1 * w4 + x2 * w4 + x3 * w4 + x4 * w4.

Pluging the values into the equation and we get 16,116: 1700 * 6 + 340 * 6 + 136 * 6 + 510 * 6 = 16,116.

This time, we get four results for each of the four neurons in hidden layer 2. We can continue this same process for all other hidden layers if we have more hidden layers to be processed, but in this case, we only have two hidden layers and we come to an end of the hidden layers processing, so we need to normalize the four results by adding them all up and pass the result on to the output layer as the final output result. I won't do the actual math result for the output layer since it is self-explanatory.

Perceptron

Perceptron, invented in 1957 by Frank Rosenblatt at the Cornell Aeronautical Laboratory, is the simplest neural network possible: a computational model of a single neuron output. A perceptron consists of one or more inputs, a some sort of computational processor, and a single output.

What we've learned thus far is called a perceptron neural network -- a neural network that has one or more inputs, one or more hidden layers, and only one output. If you hear people mentioning a perceptron neural network, that's what they mean: a neural network that has only one output.

So a key point to remember is that if a neural network has only one ouptut it is called a perceptron neural network. Perceptrons are incredibly limited in their abilities. A perceptron can only solve linearly separable problems.

What's a linearly separable problem?

To avoid getting in too deep into the theory and techical aspect of a perceptron neural network and the use of the term "linearly separable problem," I will defer it to be discussed later. Note that the use of the concept of "perceptron" in a neural network is not that significant beside the concept of a "linearly separable problem," and you don't need to worry about emphasizing the term when dealing or talking about neural network in general. For the rest of the tutorial, you probably won't hear me mentioning it that much--only when it is necessary to do so when we discuss the concept of a "linearly separable problem."

In Summary



The leftmost layer in this network is called the input layer, and the neurons within the layer are called input neurons. The rightmost or output layer contains the output neurons, or, as in this case, a single output neuron. The middle layers are called hidden layers, since the neurons in these layers are neither inputs nor outputs. The term "hidden" perhaps sounds a little mysterious -- the first time I heard the term I thought it must have some deep philosophical or mathematical significance -- but it really means nothing more than "not an input or an output."

Another term that you might have heard of is Deep Learning. A Deep Learning refers to the depth of the hidden layers, usually more than five hidden layers and can be hundreds of hidden layers. Hundreds? Now that's very deep! I don't think anyone has implemented a program that deep thus far. Three to five hidden layers are hard enough for most of us, anything larger than five is considered deep learning.


Introduction to Biases

In a typical artificial neural network each neuron in one "layer" is connected -- via a weight -- to each neuron in the next neuron in the next layer. Each of these neurons stores some sort of computation, normally a weighted sum in previous layers [as you'd already seen how it was done].

A bias unit is an "extra" neuron added to each pre-output layer to influence the outcome of a particular neuron. Bias units aren't connected to any previous layer and in this sense don't represent a true "connected" neuron. Biases are units that are added to the result of the weighted sum to influence the outcome of the output of a particular neuron in a particular layer.

Think of a bias as an ingredient of a cooked food to make food tastes much better. For example, you put some salt, pepper, chredded cheddar cheese, etc, to your cooked food (e.g., fish, spaghetti, sirloin, rips, etc) to make it more delicious.

Biases are optional inputs and not required to be added to any neuron in any layer if the neural network doesn't need it. You will run into some neural network programs that don't use biases and also you will run into some that will require the use of biases.

Let's start with a very simple diagram of a neuron with a bias:



As you can see, the neural network contains one input, one weight, one bias, and one output neuron. From the diagram, you know the drill: you do a weighted sum and once you got the sum, you add a bias value to it and pass it on to the output.

Simple enough?

Here is a two-input neuron:



Again, you know the drill: you do a weighted sum for both the input neurons and once you got the sum, you add a bias value to it and pass it on to the output.

Here is the same two-input neuron with the labels of the attributes:



As you can see within the huge circle the equation is given: f(w1 * x1 + w2 * x2 + b1).

The 'f' before the equation is a symbol to represent a function. In this case, the function is to perform the weighted sum and add the bias to it.

Thus far we've only showed only one neuron in the first hidden layer. No big deal, we can use the examples shown thus far to implement as many hidden layers with as many neurons in each hidden layer as we need by doing the usual weighted sum and tack on a bias for each hidden layer that contain any number of neurons. See the diagram below:



As you can see, we have 4 input neurons and a bias input at the top as a red circle with the value of 1. The bias values are arbitrarily set by the programmer and depending on the neural network program logic, the bias value can be whatever the logic dictates. Think of an analogous example of food tastes earlier: you put too much or too little salt, the food doesn't taste good, so you have to put just the right amount of salt in order to get the food to taste good. The bias is the same thing.

We also have 4 neurons in the first hidden layer. If we have more hidden layers, we can just use this diagram as an example and implement them as we did here. I think you know the drill.

The Output:

Again, biases are optional and if your output needs a bias, you'll have to implement one, too:



Notice that in the diagram the biases are shown at the bottom with the values of +1. The biases can be positive or negative, depending on your application's logic. In this diagram, the biases are positive or increase the result further. Remember the salt and pepper? In this example, we're adding two biases: salt and peppper, respectively.

Introduction to Weight

In machine learning, a weight is a criterio that you set to influence the outcome of the input. For example, if the input is 5 and you set the weight criterio at 2 then the outcome of the input (5) is twice as large (5 x 2 = 10). It weights the input to produce a different outcome.

The most difficult thing to do in setting the weight is to come up with what weight you should set for your particular criterio for your particular application. It amounts to a trial-and-error type of guesswork on your part to come up with a reasonable set of weights. To illustrate this, let's see an example.

Suppose that your boss asks you to write a machine learning program for a client of the company to perform an insurance policy to determine how much it should charge a particular prospective policy holder. You begin by assemblying all the criterios and assign each criterio a weight. This should looks like the following:

There are three input neurons for the prospective policy holder:

  • Male. Males are typically more aggressive drivers than females so the weight should be higher than females. So we'll give males a 2 as the input neuron.

  • Female. Females are typically less aggressive drivers than males so the weight should be lower than males. And we'll give females a 1 as the input neuron.

  • Bias. We'll give it a 1. Biases are optional but in this example I elected to use it. In a real insurance policy program we probably won't need to implement the biases. Or [in your real insurance policy program] you could use a bias as a special discount to special groups of drivers; for example, drivers who have special or extra trainings, such as the "Smith System", or for drivers who are also hold other classes of driver license, such as class, A, B, or C.

The next input neurons are hidden layers for the prospective policy holder. And we'll start with the first hidden layer. This is for the age group neurons. Again, younger drivers tend to be more reckless drivers than older drivers according to statistics. So we'll have to assign a weight scale for each driver using a scale of 0 to 10, with 10 being the most reckless drivers and 0 being the very least or non-reckless drivers:

  • Age: 18 and under. So we'll have to assign a weight scale of 10 for this age group of drivers.

  • Age: 19 - 25. So we'll have to assign a weight scale of 8 for this age group of drivers.

  • Age: 26 - 35. So we'll have to assign a weight scale of 5 for this age group of drivers.

  • Age: 36 - 45. So we'll have to assign a weight scale of 2 for this age group of drivers.

  • Age: 46 and older. So we'll have to assign a weight scale of 0 for this age group of drivers.

The next hidden layer is the second hidden layer. This is for annual income level neurons.

Generally, low income drivers tend to be more reckless drivers than higher income drivers according to statistics. So we'll have to assign a weight scale for each driver using a scale of 0 to 10, with 10 being the most reckless drivers and 0 being the very least or non-reckless drivers:

  • $0 - $9,999. So we'll have to assign a weight scale of 10 for this income group of drivers.

  • $10,000 - $29,999. So we'll have to assign a weight scale of 8 for this income group of drivers.

  • $30,000 - $49,999. So we'll have to assign a weight scale of 5 for this income group of drivers.

  • $50,000 - $99,999. So we'll have to assign a weight scale of 2 for this income group of drivers.

  • $100,000 - up. So we'll have to assign a weight scale of 0 for this income group of drivers.

Now that we have all the criterios and its weights, we can plug the values in the equations as we did in the previous sections.

Notice that I'm recycling the old diagram to illustrate the example. I'm too lazy to draw another one.

The three input neurons on the left side, from top to bottom, are male (2), female (1), bias (1).



If you look at the diagram above, it has three input neurons [including a bias input] and two hidden layers, each having four neurons. But I intentionally created five neurons each for both of the hidden layers because I wanted to illustrate that hidden layers can have any number of neurons based on your application's criterio. I could have made the two hidden layers four neurons each or I could have made them any number of neurons based on the application's criterio.

That's what happens when you're too lazy to draw a new diagram: you have to deviate from the reality.

If I were to teach a live class, I would cut the lesson off right now and instruct my students to do a homework by computing the output of this insurance policy program. Everything is all setup and ready to be computed to get the final result.

Hint: Each result should produces a unique result for the majority of the time because each driver's profile is unique, such as age group, income, and gender [the Oxford comma stylistic grammar writing.]

To Do:

As an exercise further, you can implement additional hidden layers by including more criterios, such as a credit score of the prospective drivers and driving history, e.g., if any past accidents, traffic violations, etc. For example, to implement the credit scores as the third hidden layer, you can set up the criterios like the following.

The lower the FICO score for the prospective drivers the more reckless drivers can be according to statistics:

  • FICO Score: lower than 500. So we'll have to assign a weight scale of 10 for this FICO score group of drivers.

  • FICO Score: 500 - 549. So we'll have to assign a weight scale of 8 for this FICO score group of drivers.

  • FICO Score: 600 - 649. So we'll have to assign a weight scale of 5 for this FICO score group of drivers.

  • FICO Score: 650 - 699. So we'll have to assign a weight scale of 2 for this FICO score group of drivers.

  • FICO Score: 700 - 749. So we'll have to assign a weight scale of 1 for this FICO score group of drivers.

  • FICO Score: 750 and higher. So we'll have to assign a weight scale of 0 for this FICO score group of drivers.

To implement the past driving history as the fourth hidden layer, you can set up the criterios like the following.

Again, the more traffic incidents for the prospective drivers the more reckless drivers can be according to statistics:

  • Traffic Violations: 1 or more in past 12-month or 3 or more in past 5 years. Notice the use of 'OR'. So we'll have to assign a weight scale of 10 for this traffic violations group of drivers.

  • Traffic Violations: none in past 12-month and 3 or more in past 5 years. So we'll have to assign a weight scale of 8 for this traffic violations group of drivers.

  • Traffic Violations: 1 in past 12-month and no more than 1 in past 5 years. Notice the use of 'AND'. So we'll have to assign a weight scale of 5 for this traffic violations group of drivers.

  • Traffic Violations: none in past 12-month and none in past 5 years. Notice the use of 'AND'. So we'll have to assign a weight scale of 0 for this traffic violations group of drivers.
There you have it! Have a go at it!

To Do:

As another exercise that will help you learn better is to come up with your own application problems to solve using the knowledge you'd learned thus far, particularly, the insurance policy example. And one of them is a problem of predicting annual income based on the number of years of higher education someone has completed.

You could come up with some rules about degree type, years of work experience, school tiers, etc. Even school choices do play a role in computing a person's income potential.

For example, for the input neurons, you could use gender: male or female, with male as a higher input number than female, because males tend to earn higher salaries, even at the entry point, according to statistics.

To implement hidden layers, you can set up rules or criterios like degree type, years of work experience, school tiers [Ivy league, graduate, undergraduate, community college, specialized schools], etc.

So I'm going to leave it idle for awhile for now. When I have spare time I will come back and give you the final output of this insurance policy program, including a complete source code writen in PHP so that you see how it is implemented.

Introduction to Forward Propagation

Forward propagation is a process of using the result from the previous layer and pass it on to the next layer. The layers processing that we learned thus far is called forward propagation. For example, if we have several layers as we did in the insurance policy example, the result from calculating the input layer -- which takes place in the first layer -- is passed on or propagated as input to the second layer to be calculated and the result from the second layer is propagated as input to the third layer, and the process of layer calculation and propagation continues to every layer until there isn't any more layers to be calculated and propagated.

So forward propagation is a process of accumulating all results and passing the result from one layer to the next until it reaches the final output -- it propagates or passes along the result from one layer to the next. Forward propagation is also known as Feed Forward propagation, and likewise, Backward propagation is also known as Feed Backward propagation.

Forward Propagation Processing Code

Now that we know how forward propagation works, let's see some code example of how it is done. I'm going to use PHP to demonstrate this, but you can translate this PHP code to any programming language of your choice.

First, we need to write a very simple class called NeuralNetwork which is the main neural network class that basically handles everything for us. Note that some of the code shown below include topics we haven't discussed yet, such as backward propagation, activation functions, etc. Here is the class:

Main NeuralNetwork Class
<?php
/**
 *  file: neuralnetwork.php
 *
 *  Simple MLP (Multi-layers Perceptron) Neural Network 
 */
class NeuralNetwork
    {
     private $input = array(); // input information
     private $hidden_layer = array(); // layers in the network

     /**
      * Constructor setting up layers
      * A calling program needs to create an instance of this class and passing
      * input layer, hidden layers, and output layer.
      *
      *  Usage:
      *
      *  $net = new NeuralNetwork([3, 25, 25, 1 ]);
      *
      *  After that, we need to call FeedForward() and BackPropagation().
      *  in this example, we pass the known value of XOR function as an array:
      *
      *  $net.FeedForward([ 0, 0, 0 ]);
      *  $net.BackPropagation([ 0 ]);
      *
      *  we can train some more:
      *
      *  $net.FeedForward([ 0, 0, 1 ]);
      *  $net.BackPropagation([ 1 ]);
      *
      *  $net.FeedForward([ 0, 1, 0 ]);
      *  $net.BackPropagation([ 1 ]);
      *
      *  $net.FeedForward([ 0, 1, 1 ]);
      *  $net.BackPropagation([ 0 ]);
      *
      *  $net.FeedForward([ 1, 0, 0 ]);
      *  $net.BackPropagation([ 1 ]);
      *
      *  $net.FeedForward([ 1, 0, 1 ]);
      *  $net.BackPropagation([ 0 ]);
      *
      *  $net.FeedForward([ 1, 1, 0 ]);
      *  $net.BackPropagation([ 0 ]);
      *
      *  $net.FeedForward([ 1, 1, 1 ]);
      *  $net.BackPropagation([ 1 ]);
      *
      * @param $input Layers of this network
      */
     // notice the type-hint which indicates $input is an array variable
     public __construct(array $input)
          {
           // initialize input layers that were passed in by the calling program
           for ($i = 0; $i < sizeof($input); $i++)
               {
                // $input argument contains: 3 inputs, 25 neurons in hidden layer 1,
                // 25 neurons in hidden layer 2, 1 output
                // store each argument in this class' array variable $input
                $this->input[$i] = $input[$i];
               }
               /*
                the for() loop above result in the following initialization:
                $this->input[0] = 3;
                $this->input[1] = 25;
                $this->input[2] = 25;
                $this->input[3] = 1;
               */

           // creates a bunch of neural network hidden layers,
           for ($i = 0; $i < count($input) - 1; $i++)
               {
                // for each argument in [count($input)], create a Layer object passing
                // this class' array variable $input
                // in other words, create one Layer object for the input layer (index 0),
                // one for the first hidden layer (index 1),
                // one for the 2nd hidden layer (index 2),
                // leaving the output (index 3) uneffected.
                // follow the for() loop iteration to make sense of all this:
                $this->hidden_layer[i] = new Layer($this->input[$i], $this->input[$i + 1]);
               }
           /*
            the for() loop above result in the following initialization:
            // input = 3, hidden layer = 25 => (3, 25)
            $this->hidden_layer[0] = new Layer($this->input[0], $this->input[0 + 1]);
            // hiddenl = 25, hiddenl = 25 => (25, 25)
            $this->hidden_layer[1] = new Layer($this->input[1], $this->input[1 + 1]);
            // hiddenl = 25, hidden layer = 25 => (25, 1)
            $this->hidden_layer[2] = new Layer($this->input[2], $this->input[2 + 1]);
            // so this last index is not iterated because of count($input) - 1, which is
            // when $i = 3. 3 < 3 is false,
            // so this last line is not executed at last iteration
            // hidden l = 25, hidden layer 2 = 25 => (1, null)
            // again, follow the for() loop iteration to make sense of all this:
            $this->hidden_layer[3] = new Layer($this->input[3], $this->input[3 + 1]);
           */
          }

     /**
      *  A feedforward for this network
      *  this function is called by the training app to kickstart the process:
      *
      *  // notice the argument is passed in as an array and the array
      *  can contain limitless size. here we pass in five layers.
      *  notice that we have two hidden layers 25 neurons each.
      *  if we have more hidden layers we can pass in more arguments seperate each
      *  argument with a comma, e.g.:  3 inputs, five hidden layers: 25, 25, 8, 4, 17
      *  one output: 1
      *
      *  for example:
      *  new NeuralNetwork([3, 25, 25, 8, 4, 17, 1 ])
      *
      *  Usage:
      *
      *  $net = new NeuralNetwork([3, 25, 25, 1 ]);
      *  calling FeedForward() passing the known answer. in this example, we're
      *  calling FeedForward() and passing the known value as an array. in this case,
      *  we pass an XOR function values: 0, 0, 0
      *  $net.FeedForward([ 0, 0, 0 ]);
      *  so all applications need to call this so called "train" function to start the process
      *  some programmers like to name this function as "train()" but I like "FeedForward()"
      *  @param $input inputs to be feed forward
      */
     // this function acts as a train() function to train or jumpstart the process
     public FeedForward($input)
          {
           // feed forward. notice the call to FeedForward--it's not a recursive call, but
           // rather, it is actually calling Layer's FeedForward($input) because
           // $this->hidden_layer[0] refers to Layer's object
           $this->hidden_layer[0]->FeedForward($input);
           // so after the above call to FeedForward($input),
           // Layer's $output should contains a weighted sum of the input
           for ($i = 1; $i < count($this->hidden_layer); $i++)
               {
                // start with the 2nd Layer object instance (index 1) and call
                // Layer's FeedForward() passing the output of layer 0
                $this->hidden_layer[$i]->FeedForward($this->hidden_layer[$i - 1]->output);
               }

           // return the output of the last layer
           return $this->hidden_layer[$i - 1]->output; // $i = 3
          }

     /**
      *  High level back propagation
      *  Note: It is expected the one feed forward was done before this back prop.
      *  @param $expected The expected output form the last feedforward
      */
     // notice that $expected is the known answer passed in by calling code
     public BackPropagation($expected)
          {
           // run over all layers backwards. notice that the for() loop starts from
           // the total number of hidden layers and iterated downward to 0
           for ($i = sizeof($this->hidden_layer) - 1; $i >= 0; $i--)
               {
                if ($i == sizeof($this->hidden_layer) - 1)
                   {
                    // doing a backward propagation output
                    $this->hidden_layer[$i]->BackPropagationOutput($expected);
                   }
                else
                   {
                    //back prop hidden
                    $this->hidden_layer[$i]->BackPropagationHidden($this->hidden_layer[$i +
                                                                               1]->gamma,
                    $this->hidden_layer[$i + 1]->weight);
                   }
               }

           //Update weights
           for ($i = 0; $i < sizeof($this->hidden_layer); $i++)
               {
                $this->hidden_layer[$i]->UpdateWeight();
               }
          } // end BackProp($expected)
    } // end class NeuralNetwork

/**
 *  Each individual layer in the ML
 */
class Layer
    {
     public $numberOfInput; //# of neurons in the previous layer
     public $numberOfOuput; //# of neurons in the current layer

     public $output = array(); //outputs of this layer
     public $input_layer = array(); //inputs in into this layer
     public $weight[][]; //weights of this layer, a two-dimensional array
     public $weightDelta[][]; //deltas of this layer, a two-dimensional array
     public $gamma = array(); //gamma of this layer
     public $error = array(); //error of the output layer

     public static $random = new rand(); //Static random class variable

     /**
      *  Constructor initilizes various data structures
      *
      *  @param $numberOfInput Number of neurons in the previous layer
      *  @param $numberOfOuput Number of neurons in the current layer
      *
      *  note that $this->input refers to NeuralNetwork's member array variable $input
      *  // input = 3, hidden layer = 25 => (3, 25)
      *  $this->hidden_layer[0] = new Layer($this->input[0], $this->input[0 + 1]);
      *  // hiddenl = 25, hiddenl = 25 => (25, 25)
      *  $this->hidden_layer[1] = new Layer($this->input[1], $this->input[1 + 1]);
      *  // hidden l = 25, hidden layer 2 = 25 => (25, 1)
      *  $this->hidden_layer[2] = new Layer($this->input[2], $this->input[2 + 1]);
      *  // so this last index is not iterated because of count($input) - 1, which is
      *  // when $i = 3. 3 < 3 is false
      *  // hiddenl = 25, hidden layer = 25 => (1, null)
      *  $this->hidden_layer[3] = new Layer($this->input[3], $this->input[3 + 1]);
      */
     public __construct($numberOfInput, $numberOfOuput)
          {
           $this.numberOfInput = $numberOfInput; // 3
           $this.numberOfOuput = $numberOfOuput; // 25

           //initialize data structures
           // these need to be refined and probably involve matrix manipulation
           // or we can use for loops to initialize the matrix:

           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                for ($j = 0; $j < $this->numberOfInput; $j++)
                    {
                     // need to refine these
                     $this->weight[$i][$j] = 0;
                     $this->weightDelta[$i][$j] = 0;
                    }
               }

           // all it does above is initializing the array elements to their default values.
           // all the array elements are initialized to zero.

           $this->InitilizeWeight(); //initilize weights
          }

     /**
      *  Initilize weights between -0.5 and 0.5
      */
     public InitilizeWeight()
          {
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                for ($j = 0; $j < $this->numberOfInput; $j++)
                    {
                     // I need to refine this. It doesn't seem right!
                     $this->weight[$i][$j] = rand(- 0.5, 0.5);
                    }
               }
          }

     /**
      *  Feedforward this layer with a given input
      *
      *  @param $input The output values of the previous layer
      */
     public FeedForward($input)
          {
           // initialize the layers which can be used for backward propagation
           $this->input_layer = $input;

           //feed forward
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                $this->output[$i] = 0;
                for ($j = 0; $j < $this->numberOfInput; $j++)
                    {
                     // this is the output sum of the activation function: sigmoid, tanH,...
                     // this is where we can add a bias to the output sum
                     // $this->input_layer[$j] * $this->weight[$i][$j] + $this->bias[$j]
                     $this->output[$i] += $this->input_layer[$j] * $this->weight[$i][$j];
                    }

                // I need to refine and maybe use sigmoid() instead
                //$this->output[$i] = (float)Math.Tanh($this->output[$i]);
                $this->output[$i] = call_user_func_array(array('sigmoid', $this->output[$i]);
               }

           // in the calling code only returns output of the last layer is used even though
           // we return the full array of result
           return $this->output;
          }

     /**
      *  Activation functions.
      *
      *  You can use other activation functions as well: sigmoid(), ReLU(), softmax, etc.
      *
      *	 public function sigmoid($x)
      *       {
      *        return 1 / (1 + pow(M_E, -$x));
      *       }
      *
      *  a derivative of sigmoid()
      *  
      *  public function dsigmoid($y)
      *       {
      *        // return sigmoid($x) * (1 - sigmoid($x));
      *        return $y * (1 - $y);
      *       }
      *
      *  ReLU
      *
      *  public function relu($x)
      *       {
      *        //$x = $x > 0 ? 1 : 0;
      *        return $x > 0 ? 1 : 0;
      *       }
      *
      *  TanH:
      *
      *  public function getTanH($x)
      *       {
      *        // return the computed tanH()
      *        return tanh($x);
      *       }
      *
      * Or use it directly:
      *
      *      echo tanh(M_PI_4);    // output:  0.65579420263267
      *      echo tanh(0.50);      // output:  0.46211715726001
      *      echo tanh(-0.50);     // output: -0.46211715726001
      *      echo tanh(5);         // output:  0.9999092042626
      *      echo tanh(-5);        // output: -0.9999092042626
      *      echo tanh(10);        // output:  0.99999999587769
      *      echo tanh(-10);       // output: -0.99999999587769
      */

     /**
      *  TanH derivative
      *
      *  @param $value An already computed TanH value, for example: 0.65579420263267
      *
      *  Notice that to use this TanHDer() you first have to get the value of tanh() and
      *  then call this function passing the computed value to it. See example above.
      */
     public TanHDer($value)
          {
           return 1 - ($value * $value);
          }

     /**
      *  Back propagation for the output layer
      *
      *  @param $expected The expected output
      */
     public BackPropagationOutput($expected)
          {
           //Error derivative of the cost function
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                $this->error[$i] = $this->output[$i] - $expected[$i];
               }

           //Gamma calculation
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                $this->gamma[$i] = $this->error[$i] * $this->TanHDer($this->output[$i]);
               }

           //Caluclating delta weights
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                for ($j = 0; $j < $this->numberOfInput; $j++)
                    {
                     $this->weightDelta[$i, $j] = $this->gamma[$i] * $this->input_layer[$j];
                    }
               }
          }

     /**
      *  Back propagation for the hidden layers
      *
      *  @param $gammaForward the gamma value of the forward layer
      *  @param $weightFoward the weights of the forward layer
      */
     public BackPropagationHidden($gammaForward, $weightFoward[][])
          {
           //Caluclate new gamma using gamma sums of the forward layer
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                $this->gamma[$i] = 0;

                for ($j = 0; $j < count($gammaForward); $j++)
                    {
                     $this->gamma[$i] += $gammaForward[$j] * $weightFoward[$j, $i];
                    }

                $this->gamma[$i] *= $this->TanHDer($this->output[$i]);
               }

           //Caluclating detla weights
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                for ($j = 0; $j < $this->numberOfInput; $j++)
                    {
                     $this->weightDelta[$i, $j] = $this->gamma[$i] * $this->input_layer[$j];
                    }
               }
          }

     /**
      *  Updating weights
      */
     public UpdateWeight()
          {
           for ($i = 0; $i < $this->numberOfOuput; $i++)
               {
                for ($j = 0; $j < $this->numberOfInput; $j++)
                    {
                     // learning rate is hardcoded to 0.033
                     $this->weight[$i, $j] -= $this->weightDelta[$i, $j] * 0.033f;
                    }
               }
          }
    } // end class Layer
?>

Introduction to Backward Propagation

Backward propagation, as the name implies, propagates backward from the output layer and traversing backward to the input layer. To propagate backward we need to know the output result, which means that backward propagation is done after the forward propagation; because we need to know the result of the output so that we can use the result to calculate how many steps to go backward. In other words, to walk backward, we need to know how many steps we walk forward. Make sense?

How do we determine how many steps that we walk forward or backward?

In machine learning, there is a classification concept called supervised and unsupervised learning. In a brief description, a supervised learning is where you classify the data for the machine to use that data to learn from.

In other words, you have a set of data and you fetch that data into the computer for it to use that data to learn and come up with the calculation that is as close to the data set (or model) as possible. Quite the opposite, in an unsupervised learning, you don't provide a set of data or model for the computer to learn from but instead the computer will guess on its own using algorithm you write. More on these later.

I don't want to dig too deep into supervised and unsupervised learning concept right now and will defer the topics to be discussed later in its entirety. In a supervised learning, we supply a known answer called a model to the problem and have the program calculates the layers and come up with the final result as close to the known answer as possible.

In other words, you tell the program: here is the final model that I want you to caculate your layers and make them fit my model. You show the computer your model and have the computer sees that model and learn to adjust its calculations to fit the model that you shown to it. Backward propagation is the heart and soul of machine learning using both supervised and unsupervised learning concepts.

So, to answer the question posed above, we use the output result as the starting point to calculate the total steps to count backward. To calculate how many steps to go backward, we subtract the output result from the known answer. The known answer is the model that you give it to your program to learn, and the output result is the layers processing that we'd learned in the previous sections.

For example, if your known answer or model is 100 and the result of the output layer is 80, then the steps backward is 20 (100 - 80). This 20 difference is called the error. Had the difference is zero, the propagation backward is not necessary because the layers processing did its job by getting the result to fit the model, and, therefore, the program does not need to learn and adjust the error to a minimum.

So, the goal of the calculated layers is to have the error of 0 (zero) or close to it. By the way, the function that calculates the error is called the error function, and also known as the loss function, or the cost function. The three functions take the model (or known answer) and subtract the output from it to get the error, loss, or cost.

When they say the error, loss, or cost function, they really mean the same thing and they are being used interchangibly. With loss function calculates the loss of the model or how close to the model. And with the cost function calculates the cost of being accurate of the model or the accuracy (cost) of the model.

The known model is an arbitrarily value you set based on your program logic. For example, in the insurance program we can come up with a value of 500 or 1000 (or any number that seems reasonable) and subtract the result of the output from it. Once we get the result from the subtraction we can do some calculations to finalize or normalize the result.

From there, whatever criterio you come up with for your insurance policy calculations logic is up to you to get the final result of your program. In other words, your insurance policy criterio dictates how you go about in finalizing your final result or output.

At this point, the insurance policy discussion has reached its end and I won't use it in the discussion going forward from now on; because it won't work in the real world machine learning scheme of thing because the output number is too large to fit in the activation function scheme of thing. In order for the insurance program (as it stands right now) to work it needs to normalize the output number to be between 0 and 1 -- hence, the upcoming discussion of probability is relevant.

It was used to help you understand the concept of hidden layers and forward propagation. Backward propagation is a different story and it gets much more complex. Nonetheless, what we've learned thus far stays relevant for the ensuing topics.

Once we have the error, we can propagate backward using partial derivative calculus. In other words, we take a partial derivative of the error to find the steps backward. That sounds very scary: partial derivative? But don't be frightened by the look or sound of it, because once you've seen how it is done it becomes trivial; however, if you intend to program robust and powerful machine learning programs, you should take a brief tutorial on the web on the topic of partial derivative calculus.

A derivative (or partial derivative for that matter) is merely a rate of change from one point of propagation to the next. In other words, the partial derivative of the error is the rate of change in steps to propagate backward.

As far as backward propagation is concern, there is more to come. The description just described is just a brief overview to help you understand the concept. You will encounter the use of backward propagation on virtually every program you write because it is the cornerstone of machine learning.

Introduction to Probability

I'm being a little lazy for this tutorial, and, therefore, I'll encourage you to watch the following excellent tutorials on YouTube. Machine learning makes use of probability a lot, so you need to be familiar with the concept: Machine Learning: Probability. Machine Learning: A Probability is a Number Between 0 and 1. Machine Learning: A Probability Line is a Number Between 0 and 1. Machine Learning: Why probability is always betwwen 0 and 1?

Introduction to Activation Functions



Introduction to Supervised Learning



Introduction to Unsupervised Learning



Introduction to Linearly Separable Problem



Introduction to Gradient descent

To be continued ..... more to come!

Please stay tuned!

What is a blockchain?

Before I answer that I want to dig deeper into how blockchain got its idea and foundation that led to the now famous lexicon bitcoin. Blockchain owes its origin to the Chinese Freedom struggle of the June 4, 1989, in Beijing's Tiananmen Square, in which, Chinese tanks rolled into the square to crush a student-led protest movement calling for greater political freedom; and as a result, the incident caused thousands to be imprisoned or killed.

The western world saw that horror incident on TV and began to find a way for those Chinese students to communicate with each other without allowing their government censorship on them or eavedropping on them. The solution they came up with was the peer-to-peer networking. Peer-to-peer networking was not new then but it was still in its infancy and it needed more works to be done to make it more secure and robust. The Tiananmen Square incident really accelerated the development of the peer-to-peer communication network tremendously.

By 1990, secure and robust communication networks popped up all over the places, and one type of communications in particular was the abilities to enable files sharing among the peer-to-peer networking individuals. Since then, peer-to-peer file sharing networking became the dominant force for people to share communications over the internet freely without government censorship. Peer-to-peer file sharing networking like BitTorrent, uTorrent, Gnutella, VoIP, Pirate Bay, etc, are bourne out of the result of the Tiananmen Square incident.

Also among them was a peer-to-peer networking called Free Net which is an anonymous peer-to-peer data-sharing network like BitTorrent, but it is used mainly as a private internet server or as a "Your Own Private Internet," if you look at it that way. You can use it to store/retrieve data securely without government censorship. It assigns all uploaded data a unique key, slices the data into small, encrypted chunks, and scatters them across different computers on the network. This is the basic idea for the blockchain technology.

So to answer the question posed earlier: the description of the peer-to-peer networking described in the Free Net is what a blockchain really is.

To help you understand the concept of blockchain better, here are brief videos that explain it very well. The basic concept of the blockchain technology The basic concept of the blockchain technology.

About the Free Net

To store pieces of data (also called blocks), you attach a unique key to each unique piece of data and attach it to the already existed chain in the world wide network of computers that scattered all over the world. Each unique key is encrypted and decrypted by the owner of the data so that no one is able to access that data without knowing the actual key.

When someone wants to access a piece of data, say, a document or a photograph, they "fetch" or retrieve it from the network using a unique key assigned to that piece of data.

Remember that each piece of data (also called block) has a unique key attached to it and that unique key is attached or chained to another individual block to form a chain, hence a blockchain. The blocks are sort of a linked list of long chain of blocks containing millions and billions of blocks from a variety of sources or owners that scattered all over the world.

This so-called linked list is actually a Distributed Hash Table that stores data using a global id system.

So this is how the Free Net works: it stores blocks of data and chains them together in a linked list.

That fetch/retrieval request is routed through intermediary network computers that don't store records of the request, ensuring that no single computer knows the contents of any one file.

This fetching system is very similar to how your Web browser fetches websites from the internet. In fact, once you have the Freenet client running on your PC, you can use most commercial Web browser -- like IE, Firefox or Chrome -- to browse files and websites on Freenet.

Next, head over to the Freenet Project website by Google it or via this url link: https://freenetproject.org/index.html and download the Freenet client for your operating system. The installer will walk you through the setup process, with excellent explanations of your options.

You'll have to decide whether to use Freenet in friends-only (or darknet) mode for maximum privacy. This mode lets you connect to Freenet only through trusted friends with whom you exchange encryption keys, which makes it very difficult for anyone to track what you're doing. It also creates a traffic bottleneck that throttles your download speeds.

The Friends-Only mode was designed specifically with the Tiananmen Square incident in mind so that to enable those Chinese students to communicate with each other without their government eavedropping on them.

Once the Freenet client is setup and running, you right-click the client icon in the Windows taskbar and select Open Freenet to access the welcome page. The rest is self-explanatory. Give it a try.

Hope you understand what a blockchain is; it's a different way of explaining it. My way of explaining it!!!

Next up is the technical aspect of the blockchain, including code examples in PHP.

To warm you up for my upcoming tutorial on the code implementation of the blockchain, here are series of very good videos (5 of them) that show it very well using Javascript. The basic implementation of the blockchain technology using Javascript.

Implementation of Blockchain using PHP

I hope you watched the videos series given above because it helps you understand the PHP code I'm about to show you next.

So let's start with the block class which contains the individual blocks in the chain. Remember that a blockchain is made up of blocks (or building blocks) and the below class Block is that individual building block that can be used to create individual blocks to link or chain them together to form a blockchain.

This PHP implementation of the blockchain is devoid of a P2P network implementation, and, therefore, is not a full functional blockchain application. A complete blockchain application implementation will need a P2P network to work with so that this (or any) PHP blockchain implementation can interact with a P2P network.

So we need to implement a P2P networking application to make this PHP implementation of the blockchain functions properly and fully. The implementation of P2P networking is beyond the scope of this brief introductory tutorial. You might want to Google the term "P2P networking tutorials" to learn about it.

The block class has a normal constructor, which contains four arguments: the block variable $index, current time $timestamp, current transaction $transaction, and lastly the previous block $previousHash.

These four arguments are very important to a blockchain because these four items get linked or chained or referenced throughout the course of the blockchain flow lifecycle.

In other words, each transaction you make, you create a block of the chain, or more specifically, you create an instance of this class Block, which contains all the necessary information to allow you to complete the transaction. So this class is the main building block of the blockchain.

This class also contains two methods, calculateHash() and mineBlock(), which are self-explanatory, if you follow the code flow.

<?php
/*
 * file: block.php
 *
 * a complete blockchain implementation will still need a P2P network
 * so we need to implement a P2P network.
 */

class Block
    {
     public __constructor($index, $timestamp, $transaction, $previousHash = '')
          {
           $this->index = $index;
           $this->previousHash = $previousHash;
           $this->timestamp = $timestamp;
           //$this->data = $data;
           $this->transaction = $transaction;
           $this->hash = $this->calculateHash();
           $this->nonce = 0;
          }

     public function calculateHash()
          {
           // return hash('SHA256', strval($this->previousHash .
           // $this->timestamp . json_encode($this->transaction) . $this->nonce));
           return hash('SHA256', $this->previousHash .
                        $this->timestamp . ((string)$this->transaction) . $this->nonce);
          }

     // Implementing Proof-of-Work
     public function mineBlock($difficulty)
          {
           // takes the array elements, converts to string and concatenates 0 to it
           while (substr($this->hash, 0, $difficulty) !== str_repeat("0", $difficulty))
               {
                $this->nonce++;
                $this->hash = $this->calculateHash();
               }

           //echo("BLOCK MINED: " + $this->hash);
          }
    } // end class Block
   

The main class Blockchain

Here is the heart and soul of the class for the blockchain.
<?php
/*
 * file: blockchain.php
 *
 * a complete blockchain implementation will still need a P2P network
 * so we need to implement a P2P network.
 */

/**
 *  usage:
 *
 *  $coin = new Blockchain();
 *  $coin->createTransaction(new Transaction('address1', 'address2', 100));
 *  $coin->createTransaction(new Transaction('address2', 'address1', 50));
 *
 *  echo('\n Start mining...');
 *  $coin->minePendingTransaction('john-doe-address');
 *
 *  echo('\nBalance of John Doe is') . $coin->getBalanceOfAddress('john-doe-address');
 *
 *  echo('\n Start mining again...');
 *  $coin->minePendingTransaction('john-doe-address');
 *
 *  echo('\nBalance of John Doe is') . $coin->getBalanceOfAddress('john-doe-address');
 */
class Blockchain
    {
     public $chain = array();

     public __constructor()
          {
           // this chain should hold an array of object of genesis block
           // should be without the "[]"
           // need to refine.

           // $chain holds an array of Block objects ... lots of it.
           // this is where we hold blocks of transaction.
           $this->chain = [$this->createGenesisBlock()];  // need to refine this
           $this->difficulty = 2;
           // this array propery is assigned transactions by minePendingTransaction() below
           $this->pendingTransaction = array();
           $this->miningReward = 100;
          }

     public function createGenesisBlock()
          {
           // the return statement just returns an instance of Block.
           // so the constructor that calls this function assigns an instance of Block and
           // that is it!

           // need to refine this call: notice that only three arguments are passed in!
           // this is because the fourth argument is optional: $previousHash = ''

           // need to refine these calls!
           //return new Block(0, strtotime("2017-01-01"), "Genesis Block");
           return new Block(new DateTime('2000-01-01'), [], "0"); // [] short cut array
          }

     public function getLatestBlock()
          {
           // count the # of array elements in the chain by subtracting 1 to get the
           // last element in the array and therefore getting the last block.
           // array element starts at 0, 2nd element is 1, 3rd element is 2, etc.
           return $this->chain[count($this->chain) - 1];
          }

     public function minePendingTransaction($miningRewardAddress)
          {
           // $this->getLatestBlock()->hash refers to the chain's property hash which
           // holds the block's hash strings
           $block = new Block(new DateTime(), $this->pendingTransaction,
           $this->getLatestBlock()->hash;
           $block->mineBlock($this->difficulty);

           echo ('Block successfully mined!');
           // push the chain onto the block to be stored in the blockchain serial
           array_push($this->chain, $block);

           // storing the transactions in this class's
           // array property $this->pendingTransaction
           $this->pendingTransaction = [
                                        new Transaction(null, $miningRewardAddress,
                                                        $this->miningReward)
                                       ];
          }

     // create a transaction passing an instance of the Transaction object containing
     // $fromAddress, $toAddress, $amount
     // and then push this transaction object onto the array list: pendingTransaction
     // createTransaction() receives a 'new Transaction("address1", "address2", 100)'
     // instance object as its argument
     public function createTransaction($transaction)
          {
           // storing the transactions in this class's
           // array property $this->pendingTransaction
           array_push($this->pendingTransaction, $transaction);
          }

     public function getBalanceOfAddress($address)
          {
           $balance = 0;

           foreach ($this->chain as $block)
                 {
                  foreach ($block->transaction as $trans)
                        {
                         if ($trans->fromAddress === $address)
                            {
                             $balance -= $trans->amount;
                            }

                         if ($trans->toAddress === $address)
                            {
                             $balance += $trans->amount;
                            }
                        }
                 }

           return $balance;
          }

     public function isChainValid()
          {
           for ($i = 1; $i < count($this->chain) + 1; $i++)
               {
                $currentBlock = $this->chain[$i];
                $previousBlock = $this->chain[$i - 1];

                if ($currentBlock->hash !== $currentBlock->calculateHash())
                   {
                    return false;
                   }

                if ($currentBlock->previousHash !== $previousBlock->hash)
                   {
                    return false;
                   }
               }

           return true;
          }
    } // end class Blockchain
   

Transaction

<?php
/*
 * file: transaction.php
 *
 * a complete blockchain implementation will still need a P2P network
 * so we need to implement a P2P network.
 */

class Transaction
    {
     public __constructor($fromAddress, $toAddress, $amount)
          {
           $this->fromAddress = $fromAddress;
           $this->toAddress = $toAddress;
           $this->amount = $amount;
          }
    } // end class Transaction
   

Peer-to-peer network tutorials

Here are some of the video tutorials that you can get started learning peer-to-peer network:

Peer to Peer Network: P2P Network - Fundamental Concepts Peer to Peer Network: What is a peer to peer system? Peer-to-peer (P2P) Networks - Basic Algorithms Peer-to-peer (P2P) Networks: Routing in Distributed Hash Tables Peer-to-peer (P2P) Networks: Hash Tables Introduction to Decentralized P2P Apps Peer to Peer: MIT 6.824 Distributed Systems (Spring 2020) Peer to Peer: What is a distributed system?

Peer-to-peer network libraries

Very surprisingly, to say the least, there aren't many open-source PHP peer-to-peer network libraries out there on the Internet. So now the choices are to write your peer-to-peer network applications in other languages, say, Javascript, Node.JS, or even in a language called Go! (a not very well-known language but it is very suitable for writing peer-to-peer network applications.) This language (Go!) is built specifically for programming peer-to-peer network applications.

Anyhow, here are some libraries:

Peer to Peer Network Libraries in PHP

Peer to Peer Network Libraries in Go!

Peer to Peer Network Examples in Go!

Peer to Peer Network Tutorials 'README' File in Go!

Javascript Blockchain Libraries

As you might have already knew that PHP is not a language that is suitable for programming blockchain applications. However, Javascript is very much suitable for programming blockchain applications since it does have multithread capabilities, whereas PHP does not.

So if you are familiar with the language of Javascript, particularly Node.JS, you can use Javascript to program your blockchain applications. Here is a library for building blockchain applications using Javascript, particularly using Node.JS, which uses a native Javascript language.

Lisk: the blockchain application platform

There you have it! A blockchain application platform for building blockchain applications.


Introduction to RSA Encryption

The RSA is a three-letter acronym derived from the names of its inventors at MIT in the 1970s using their last name's first letter as an acronym: Ron Revest, Adi Shamir, and Leonard Adleman.

The RSA encryption is a military-grade encryption scheme that is being widely used throughout the world, especially in banking applications and other top secret applications.

The RSA uses two keys: one called a public key and another called a private key. We'll discuss about keys later. For now, let's discuss about prime numbers.

The RSA uses prime numbers to create keys to encrypt and decrypt information.

For those of you who are not math inclined, or those who are not really into the historical and theoretical aspects of the RSA encryption, feel free to jump ahead to the implementation section.

For the rest, this section is probably of most significance (and of most importance) to those of you who are working with encryption or security in general. Having a detailed knowledge of how things really work (and why) is essential if you intend to keep your security systems one step ahead of hackers.

What are prime numbers?

Prime numbers have been of interest since the ancient Greek philosophers. However, they were not of interest for theoretical purposes until the latter half of the twentyth century: the 1960s and 1970s when computer technology was beginning to catch fire.

Researchers saw the vulnerability of the information age that computer technology brought and they began to find ways to make the information age secure. A group of researchers at MIT, namely Ron Revest, Adi Shamir, and Leonard Adleman, came on top and their fruit of labor is now being used widely throughout the world.

Let's start with the simplest definiton of a prime number. Prime numbers were discovered by Euclid, sometimes called Euclid of Alexandria.

Euclid was an Ancient Greek philosopher who was born in 300 BC. He was a super, super brilliant mathematician who contributed to the world of mathematics in epic proportion.

In the book VIII of Elements, Euclid defined a prime as a number that has no whole-number divisors other than 1 and the number itself. A few examples of prime numbers would be 2, 3, 5, 11, 13, etc.

As you can see, neither 2, 3, 5, 11, or 13 are divisible by any number other than 1 and itself.

On the other hand, a number that is not a prime is said to be a composite.

What is a relative prime number?

Another important definition is called relative prime. But some textbooks call it coprime. I call it relative prime.

A prime number is considered a relative prime to any other number if it does not divide that number. Make note: It does not divide that number! That number is not divisible by a prime!

In other words, a prime number has some relative numbers out there. It has lots of relatives out there. Somewhere in the world of numbers, there are numbers that are relative to this prime number.

Sort of saying a person born without knowing how many relatives he/she has in the world and that person needs to go out and find his/her relatives out there in the world.

The same thing is also true for prime numbers: They need to go out and find their relatives among the numbers in the set.

A prime number cannot divide a number if that number is considered to be a relative prime to a prime number.

This is sort of saying: A person out there whose one or both of his/her parents are not the same as the parent or parents of the person seeking to find relatives CANNOT be a relative to the person seeking to find relatives.

A simplier way of say is that, a person has to share of at least one parent with another person in order to qualify as a relative to that person.

Let's put it this way: If a prime number p is a relative prime to a number n, then: n mod p is not equal to zero. The two numbers are not divisible by one another. We can say that p is a relative prime to a number n or vice versa.

Note: mod is a remainder division function representing modulus operation. So the goal of mod is to return the remainder of a division. For example, 4 mod 2 = 0, 5 mod 2 = 1, 10 mod 5 = 0, and 10 mod 3 = 1 (because 10 divided by 3 resulted in the quotient of 3 with the remainder of 1.)

So if n mod p is equal to zero, it means that n is divisible by p. But n cannot be divisible by p in order to be considered as a relative prime number to p.

Knowing that, we can basically formulate the following three rules or theories or propositions as Euclid called them.

  1. If a prime number p divides a product m * n (with m * n means m multiplies n), then p divides at least one of the two numbers m or n. See proposition 1 illustration below.


    [

    By the way, in mathematics, a product is usually written as m x n as well as mn and as well as m.n, too. The latter one with a dot "." notation.

    So all four forms: m x n, m * n, mn, and m.n are all valid forms of a mathematical product.

    You will see all of the above mathematical forms throughout this tutorial, particularly using parentheses to group multiple entities, for example:
    (p - 1)(q - 1) = (p - 1) x (q - 1) = (p - 1) * (q - 1) = (p - 1) . (q - 1)

    ]

  2. Every number can be prime or else can be expressed as a product of prime in a way unique, apart from the order in which they are written.

    This uniqueness is the key to the RSA cryptography.

    A product of prime numbers will result in a prime number as well.

  3. There are indefinitely many prime numbers (in the world of whole numbers.)

Okay, we have three propositions to prove, so let's lay them out one by one and then try to prove them:

Proposition 1:

If a prime number p divides a product mn,
then p divides at least of the two numbers m, n.

Proof:

Let the two numbers m and n multiplied by one another to make another
number o (letter o), and let any prime number p divides o.


Now we must prove that p divides m or n.

Let's assume that p does not divide m, therefore, p and m are relative primes.

Remember the definition of relative prime?

Now let's make another number e such that:

e = mn div p (we could use '/' instead of div as well)

(note: e is the number of units that p divides mn.)
(Make note: div and not mod.)
(div is a division function -- the same as '/'.)

Since p divides mn according to e, then pe = mn.

Therefore, p/m = n/e.

But p is a relative prime to m.

Therefore, they are the least of those that have the same ratio with them.
And the least divides the numbers that have the same ratio (p/n and m/e).

That is, p divides n (and m divides e.)

Similarly, we can also prove that if p does not divide n, then it must divide m.

Next up is Proposition II.

Proposition II is also known as the Fundamental Theorem of Arithmetic.

We'll prove Proposition II in two steps.

First, we can prove that a number can always be factored into primes, and then, secondly, we'll show that this process is unique; that is, there is only one prime factorization for each number.

This uniqueness is the key to the RSA cryptography.

See conclusion for similar statement at the end of Proposition II discussion for this second step.

Those are the two-step processes we are going to have to work through.

Proposition 2:

Every natural (or whole) number is either prime or can be uniquely factored as
a product of primes in a unique way.

Proof

Let's prove this using contradiction.

Let's assume that there are numbers that cannot be written as a product of primes.

Therefore, there must exist the smallest of such numbers; and we'll call it n.

By definition, n must be a natural number greater than 1.

'Nautral' means 'whole' and not fractional number.

So n = ab where a and b are natural numbers such as
a > 1 and b < n.
 
Therefore, a and b are smaller than n, so a and b can be factored into primes.

For example: n = (a - 1)(b - 1)

By substitution, n can be factored by primes.

This contradicts the assumption that there exist composite numbers that cannot be
factored into primes.

Conclusion: All natural numbers are either primes or can be written as a
product of prime numbers.

Now let's prove that this product is unique, again using contradiction.

This is the second step.

Let's assume that there are numbers that can be factored into primes in at least
two distinct "unique" ways.

Then, there must exist the smallest of such numbers, n,
where n can be represented by:

n = p1p2p3p4p5p6.....pk

OR

n = q1q2q3q4q5q6.....qk

Now let's select one of the members, say, p1.

We can say that p1 divides n, and, therefore,
it divides q1q2q3q4q5q6.....qk as well.

That means that n / p1 = q1q2q3q4q5q6.....qk / p1

But from Proposition I, if p1 divides the product q1q2q3q4q5q6.....qk,

then, p1 must divide at least one of its members, say,

q1 / p1

OR

q2 / p1

OR

q3 / p1

OR

q4 / p1

OR

qk / p1

Since all members on the right side of the equation (p1p2p3p4p5p6.....pk and
q1q2q3q4q5q6.....qk) are primes,
we can say that for a number qj (with 1jn),
the following equality holds:

p1 = qj

We can, without loss of generality, assume j = 1

Therefore, p1 = qj

The result of n / p1 is a number smaller than n, and, consequently,
from our initial assumption,
it cannot be factorized in more than one unique ways.

It can only be factorized in one unique way!

Therefore, the consequences p2.....pk and q2.....qk contain the same primes,
possibly different only in their order.

Conclusion: There is only one way to factorize a number into primes.
This uniqueness is the key to the RSA cryptogrophy.

Well, if it wasn't the uniqueness property of the  prime,
the RSA cryptography would have not been invented and
the crytography landscape of the world would have been
a lot different than today's environment.

So the uniqueness property of the prime made the RSA cryptography possible.

Proposition III

Proposition 3:

There are indefinitely many prime numbers.

Proof

Let's start with the list: p1, p2, p3, ..... of all known primes.

We must prove that this list continues forever because proposition III states
that there are indefinitely prime numbers out there.

Let's assume that we have listed all primes up to some pm.

Now consider a number p such as:

p = p1p2p3....pm + 1

Note: that is pm + 1 and not pm + 1. Be careful to not confuse the two.

Note that p1p2p3.... means a product of multiple primes.

Likewise, p1p2 means a product of two primes.

If p happens to be a prime,
then p is a prime bigger than pm (because of the product)
and the list can continue (note that p might not be the next prime after pm,
in which case, p cannot be taken to be pm + 1).

If p is not a prime,
then it must be evenly divisible by a prime (Proposition 2).

But none of the primes p1p2p3....pm divides p.

If you carry out such division, you always end up with a remainder of 1.

Therefore, p must be divisible by a prime bigger than all primes up to pm.

Conclusion: We can always find a bigger prime for any given list p1p2p3....pm.

In other words, the list of primes continues forever because there are
indefinitely prime numbers out there.

Taken together, the first two propositions form the building blocks of all natural (or whole) numbers, much like the physicist's atoms.

Knowing the prime number factorization of a number gives complete knowledge about all factors of that number.

Now that we've learned some of the fundamental properties of prime numbers, we need to learn how to find them, and -- most importantly -- how to prove that they are in fact primes.

Finding Primes

How do we go about in finding primes?

There are many ways to find primes, and their efficiency usually depends on the size of the primes in which we are interested in, or on the probability of these numbers truly being primes.

One popular method of finding primes is called Sieve of Eratosthenes, which was invented by an ancient Greek philosopher named Eratosthenes in 280 BC.

To verify that n is a prime, follow this two-step process:

  1. You look at all numbers from 2 to n. For example, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ......, n.

    Here is a PHP code fragment to list the numbers from 2 to n:

    <?php
    $n = 2147483647;
    $a = array();
    
    $a[0] = 0; // we know that this is not a prime
    $a[1] = 0; // we know that this is not a prime
    
    // we start with 2 since 0 and 1 have already been initialzied above
    
    // as you can see, it loops through $n = 2147483647 which
    // takes some time to loop through!
    
    for ($i = 2; $i < $n + 1; $i++)
        {
         // initialize all array indexes $a to 1 up to $n
         // so $a[2] = 1, $a[3] = 1, $a[4] = 1, $a[5] = 1, ...
    
         $a[$i] = 1;
        }
     ?>

    So you start with the smallest number, which is 2, and work your way upward to n.

  2. Then you eliminate all multiples of 2 up to n. For example, what is left is this: 2, 3, 5, 7, 11, 13, ......, n.

    Notice that 15 is an odd number but it is not a prime number because in the definition of prime stated earlier, it says a number cannot be divided by another number and 15 can be divided by 3 (which is 5), and, therefore, 15 fails the definition of prime.

    Likewise, 9 is not a prime number either because 9 can be divided by 3 (which is 3), and, therefore, 9 fails the definition of prime as well.

    Here is a PHP code fragment to eliminate multiples of 2 up to n:

    <?php
    $p = 2;
    
    while ($p < $n)
        {
         // step through multiples of 2
         $j = $p * 2;
    
         // variable $n is an aribitrily number you supply!
         while ($j <= $n)
             {
              // eliminate multiples of two up to $n
              // and we know that these are not primes
              // so $a[4] = 0, $a[6] = 0, $a[8] = 0, $a[10] = 0, ...
    
              $a[$j] = 0;
              $j += $p;
             } // end while ($j <= $n)
    
         do
             {
              // $p = 3, 4, 5, 6, 7, 8, 9, 10, 11, .... $n
              $p += 1;
             }
         while ($a[$p] != 1)
        } // end while ($p < $n)
     ?>

    So now what is left is this: 2, 3, 5, 7, 11, 13, ......, n.

    So what do these numbers in the list that were not eliminated mean?

    Well, we'll look at the definition of prime again, and it goes like this: A prime is a number that has no whole-number divisors other than 1 and the number itself.

    So the numbers in the list are prime numbers because they are not divisible by any other number other than 1 and themselves. So 2, 3, 5, 7, 11, 13 are prime numbers.

    That's all you have to do to find prime numbers.

Although the numbers resulting from this method are sure to be primes, this algorithm is very slow and has exponential complexity, meaning it runs exponentially in the number of digits in the number n. As you can see in the fragment code illustration above, it loops through n = 2147483647 which takes some time to loop through.

Anyhow, let's go ahead and create a function to generate prime numbers using Sieve of Eratosthenes method illustrated above.

Let's put the whole pieces of code illustrated above together to form a complete code.

Here is an implementation of the Sieve of Eratosthenes:

<?php
/**
 * finding primes using Sieve of Eratosthenes
 */

public function prime($n)
     {
      $a = array();

      $a[0] = 0; // we know that this is not a prime
      $a[1] = 0; // we know that this is not a prime
      $p = 2;

      // we start with 2 since 0 and 1 have already been initialzied above

      for ($i = 2; $i < $n + 1; $i++)
          {
           // initialize all array indexes $a to 1 up to $n, for example:
           // $a[2] = 1, $a[3] = 1, $a[4] = 1, $a[5] = 1, ...

           $a[$i] = 1;
          }

      while ($p < $n)
          {
           $j = $p * 2;

           while ($j <= $n)
               {
                // eliminate a multiple of two up to $n
                // and we know that these are not primes, for example:
                // $a[4] = 0, $a[6] = 0, $a[8] = 0, $a[10] = 0, ...

                $a[$j] = 0; // set $a[4] = 0
                $j += $p; // now increase $j by 2 
               } // end while ($j <= $n)

           // here, we're looking for primes

           do
               {
                // $p = 3, 4, 5, 6, 7, 8, 9, 10, 11, .... $n
                $p += 1;
               }
           while ($a[$p] != 1)
          } // end while ($p <= $n)

      $k = 0;
      $prime = array();

      // iterate through n again, but this time we're only
      // looking to pick out only primes

      for ($i = 2; $i < $n + 1; $i++)
          {
           // test to see if any of array index $a = 1 up to $n
           // if $a = 1 then it is a prime!
           // so store it in array $prime for later retrieval

           if ($a[$i] != 0)
              {
               $prime[$k] = $a[$i];
               $k++;
              }
          }

      return $prime;
     } // end function prime($n)

/**
 * prime() above can be called like this:
 *
 * $n = 50;
 *
 * $p = prime($n);
 *
 * foreach ($p as $value)
 *       {
 *        echo $value . " ";
 *       }
 *
 * output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
 *
 * or if $n = 100;
 *
 * output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
 *         53 59 61 67 71 73 79 83 89 97
 */
?>

Here is another implementation of the Sieve of Eratosthenes that I want to illustrate. The code illustrated above and the following code (below) will achieve the same result, so that you can pick and choose to use at your own preference.

I want to illustrate that the code above is a tidbit slower than the one below; because, as you can see, the code above has four loops that loop from 2 to n, while the one below has only three loops (but four if you count the array_fill() loop, too).

The code above, I could have chosen to use array_fill() instead of the for() loop and both codes would have achieved the same performance. However, I chose to use for() loop just to illustrate that there are many ways to achieve the same result and also to point out that there are performance discrepancies between the two.

In the end, there isn't much meaningful differences in performance between the two -- only the one below is a very tiny, slightly faster only because of the use of the array_fill().

Because of the "computationally intensive" problem, it is generally a normal practice to generate primes randomly rather than using loops (four loops in this case).

In other words, randomly choose a number and then test that number for prime. That way it can be done without loops or fewer loops.

Use Fermat's Little Theorem to test for prime. See a section called Primality Test a little bit later.

If you don't want to use Fermat's Little Theorem to test for prime, it's not the end of the world to use loops (as my illustrations show). As a matter of fact, lots of people have done so for decades without using Fermat's Little Theorem.

However, wise guys tend to choose a random number, say, 3754 (or any number), and test it for prime. That is the quickest way to create prime numbers for your RSA applications.

If you want to use random primes, here is one way to do it.

You could use the Sieve of Eratosthenes code illustrated in this tutorial to create a list of prime numbers and store them in a file or database or some other storage mediums. See my code later about using a json file to store keys.

That way, you don't have to worry about taking too long to create prime numbers on the go, because you already created them and tested them for primes before hand.

Here is one way to do it:

<?php
/**
 * First, you have to create primes using Sieve of Eratosthenes method.
 * Second, store them in a file, database, or some other mediums.
 * Third, when you need random prime numbers, just retrieve them from
 * the storage device you created in the second step.
 *
 * This way, you don't need to create prime numbers on the fly as most
 * wise guys often do!
 *
 * Here is one way to do it:
 */

// retrieve prime numbers from a storage device
// and place them in an array, for example:

$prime = array();

// assuming you're retrieving them from a database

try
    {
     // assumming $conn is an instance of a PDO

     $stmt = $conn->prepare("SELECT prime FROM primetable");

     /**
      * retrieve prime numbers from the database
      * and place them in an array variable: $prime
      */

     $prime = $stmt->execute();
    }
catch (PDOException $e)
    {
     echo 'ERROR: Cannot select data from the database: ' . $e->getMessage();
    }

// mimicking a random prime number generator

// this example assumes we're working with
// 201 prime numbers: 0 to 200

do
    {
     $i = rand(0, 200);
     $j = rand(0, 200);

     $p = prime[$i];
     $q = prime[$j];
    }
while ($p == $q) // if p == q, keep looking!

// when p and q are distinct, we stop looking and keep them!

// now you can use p and q to calculate your RSA algorithm!
// you might want to put this fragment of code in a function
// and modify it slightly to return p and q
// so that you can call it conveniently!

// or leave it "AS IS" and use the following code to store them!

// remember that p and q are secret keys, and, therefore,
// they need to be encrypted and stored in a secure medium

$data = [
         "p" => $p,
         "q" => $q,
         "date" => date("d-m-Y H:i:s") /* displays: 2016-04-26 20:01:04 */
        ];

try
    {
     $stmt = $conn->prepare("INSERT INTO keytable (p, q, date) 
                                           VALUES (?, ?, ?) ");

     /**
      * $data contains three items: p, q, date.
      * execute the place holder ? ? ?
      */

     $stmt->execute($data);
    }
catch (PDOException $e)
    {
     echo 'ERROR: Cannot insert data into the database: ' . $e->getMessage();
    }
?>

There are lots of ways to test for prime. Google Miller-Rabin algorithm to test for primes as well.

PHP has a function called gmp_prob_prime() which uses Miller-Rabin algorithm to return primality test result.

Also note that using this form ++$i is 1/3 faster than $i++, which matters for big loops. So I recommend using this form: ++$i (the pre-arithmetic operator) for most of your programming code rather than the post-arithmetic operator: $i++.

<?php
/**
 * Sieve of Eratosthenes method of finding primes
 *
 * php program to print all primes smaller than or equal to n
 *
 * $n = 2147483647
 */

public function sieveOfEratosthenes($n) 
     {
      // create a boolean array "prime[0..n]"
      // and initialize all entries as true.
      // a value in prime[i] will finally be
      // false if i is not a prime, else true.

      $prime = array_fill(0, $n + 1, true);

      for ($p = 2; $p * $p <= $n; $p++)
          {
           // if prime[p] is not changed,
           // then it is a prime
           if ($prime[$p] == true)
              {
               // update all multiples of p
               for ($i = $p * $p; $i <= $n; $i += $p)
                   {
                    // if $prime[$i] is not a prime, return false
                    $prime[$i] = false;
                   }
              }
          }

      // print all prime numbers

      for ($p = 2; $p <= $n; $p++)
          {
           if ($prime[$p])
              {
               echo $p . " ";
              }
          } 
     } // end function sieveOfEratosthenes()

/**
 * sieveOfEratosthenes() above can be called like this:
 *
 * $n = 50;
 *
 * sieveOfEratosthenes($n);
 *
 * output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
 *
 * or if $n = 100;
 *
 * output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
 *         53 59 61 67 71 73 79 83 89 97
 */
?>

Create a function that will return an array containing a range of prime numbers. Because of the way in which the algorithm works, the function above isn't possible to generate just a selection of numbers, and as you can see from the output above, the numbers must all be generated and stored in the array variable $prime.

That is not very useful if you just want one prime number to use in your application and not the whole list of primes. The following function aims to achieve that goal.

<?php
/**
 * find all the primes up to a given number using
 * the Sieve of Eratosthenes algorithm.
 *
 * @param $start The number to start searching for prime numbers.
 * @param $finish The number to stop searching for numbers.
 *
 * @return array The array of prime numbers.
 */

public function findPrimeRange($start, $finish)
     {
      // initialize the range of numbers.
      $number = 2;

      // create an array containing a range of elements from "2" to
      // "2147483647":
      // $range[2..2147483647]
      // Array ( [2] => 2 [3] => 3 [4] => 4 [5] => 5 ...... )

      $range = range(2, $finish);

      // create an array by using the key elements from first argument as 
      // key and "value" from the second argument as value

      // $prime[2] => 2, $prime[3] => 3, $prime[4] => 4, ....

      $prime = array_combine($range, $range);

      // loop through the numbers and
      // remove the multiples from the primes array.

      while ($number * $number < $finish)
          {
           for ($i = $number; $i <= $finish; $i += $number)
               {
                if ($i == $number)
                   {
                    continue;
                   }
                unset($prime[$i]);
               }
           $number = next($prime);
          }

      // slice the array into the given range

      foreach ($prime as $p)
            {
             if ($p < $start)
                {
                 unset($prime[$p]);
                }
             else
                {
                 break;
                }
            }
      return $prime;
     }

/**
 *This can be used in the following way.
 *
 * print_r(findPrimeRange(30, 50));
 * Array
 *     (
 *      [31] => 31
 *      [37] => 37
 *      [41] => 41
 *      [43] => 43
 *      [47] => 47
 *     )
 */


/**
 * PHP code to check wether a number is prime or not
 * function to check the number is prime or not
 */

public function primeCheck($number)
     {
      // we know that 0 and 1 are not primes!

      if (($number == 0) || ($number == 1))
         {
          // not a prime
          return 0;
         }

      // we know that 0 and 1 are not primes, so start with 2

      for ($i = 2; $i <= sqrt($number); $i++)
          {
           if ($number % $i == 0)
              {
               return 0;
              }
          }
      return 1;
     }

/**
 * Usage:
 *
 * $number = 31;
 * $flag = primeCheck($number);
 *
 * if ($flag == 1)
 *    {
 *     echo "Prime";
 *    }
 * else
 *    {
 *     echo "Not Prime"
 *    }
 */
?>

Check this out to find the next prime number say, if want to find the next prime number after 10, gmp_nextprime(10) will return 11. This PHP function is suiteable for looking for a certain prime number after a certain number, say, you want to find a prime number after 2436.

You could use PHP function gmp_nextprime() to your advantage to generate a list of prime numbers. For example:

<?php
/**
 * mimicking a random prime number generator
 *
 * Usage:
 *      $prime = generatePrime(100);
 *
 * for() loop will loop through 100 times and generates 100 prime numbers
 */

public function generatePrime($n)
     {
      for ($i = 0; $i < $n; $i++)
          {
           // you can make the range as wide or narrow as you want!
           // or as large or small as you want!

           $j = rand(100, 200000);

           // function gmp_nextprime() returns the next prime number after $j

           $prime = gmp_nextprime($j);

           try
               {
                // assuming $conn is a PDO object!

                $stmt = $conn->prepare("INSERT INTO primetable (prime) 
                                        VALUES (?) ");

                // execute the place holder ?

                $stmt->execute($prime);
               }
           catch (PDOException $e)
               {
                echo 'ERROR: Cannot insert data into the database: ' . $e->getMessage();
               }
          } // end for()
    } // end generatePrime()
?>

There you have it! A fast way to generate primes.

Here is more theories about generating primes.

Mathematicians for centuries have been trying to find equations for generating prime numbers, but their success has been slow and valid to only a small range of natural numbers.

Lenard Euler, the Swiss mathematician, came up with the following equation:

f(x) = x2 + x + 41, which is prime for x = 0, 1, 2, ..., 39.

This quadratic equation was the record holder for centuries as a consecutive, distinct quadratic prime-producer for an initial range of input values.

It is not, however, the current record holder. That distinction goes to this function:

f(x) = 36x2 - 810x + 2753, which is prime for x = 0, 1,..., 44.

As you have probably noticed, these functions are also very limiting in their range and are of very little or no practical use.

To be of any real use, we need a method that can produce an infinite number of primes, and of any size we want.

The best way found to deal with this problem, since there are no formulas for finding all prime numbers in sequence, is to instead find numbers that are "very likely" to be primes. Hence, testing for primes or primality.

Primality Test

If we are going to use our primes for industrial uses (e.g., encryption), we often do not need to prove that they are primes.

It may be enough to know that the probability they are composite is less than a given percentage (e.g., 0.000000000000000000000001). In this case, we can use (strong) probable primality tests.

Let's refresh our memory: A number that is not a prime is said to be a composite.

Most of these tests are based on what is known as Fermat's Little Theorem (named after a French mathematician named Pierre de Fermat (1601-1665)).

The Fermat's Little Theorem states:

If p is a prime and if a is any integer, then ap = a (mod p).

In particular, if p does not divides a, then a(p - 1) = 1.

You can't just pick a random number and use it as your RSA encryption key. It won't work. You have to test it for primality using Fermat's Little Theorem. You also can use PHP function gmp_prob_prime() which uses Miller-Rabin algorithm to return primality test result.

Basically, what Fermat's Little Theorem is trying to accomplish is to find the remainder of a number (a raise to the power of (p - 1)) by dividing a(p - 1) by p to equal 1.

That's what this equation a(p - 1) = 1 means.

And that's what the statement: "if p does not divides a, then a(p - 1) = 1" above means.

So p needs to be a prime number in order for it to be a remainder of 1.

Another way of saying is that, the left side divided by p equals to a remainder of 1. So you need to divide the left side by p until the remainder is equal to 1, then stop.

Please check out tutorials on YouTube on Fermat's Little Theorem

Let's see the proof of Fermat's Little Theorem.

Fermat's Little Theorem

Proposition:

If p is a prime and if a is any integer, then ap = a (mod p)

In particular, if p does not divide a, then a(p - 1) = 1.

Proof

Start by listing the first (p - 1) positive multiples of a

For a visual guide, see YouTube tutorials mentioned earlier.

For example:

a, 2a, 3a, .... (p - 1)a

Suppose that ra and sa are the same modulo p, then we have r = s (mod p),
so the (p - 1) multiples of a above are distinct and nonzero; that is,
they must be congruent to 1, 2, 3, ...., (p - 1) in some order.

Multiply all these congruences together and we find:

a.2a.3a .... (p - 1)a = 1.2.3 .... (p - 1) (mod p)

OR better:

a(p - 1) (p - 1)! = (p - 1)! (mod p)

Divide both sides by (p - 1)! to complete the proof.

Don't worry if you don't understand the proof! It's not important!

However, you need to know how to find the remainders of a number.
See YouTube tutorials mentioned earlier.

Conclusion: There is only one way to factorize a number into primes.

As you can see from the above proposition of the Fermat's Little Theorem, there is only one way to factorize a number into primes.

It's important to note that Fermat's Little Theorem is a compositeness test, and not a primality test; that is, it tells you for sure if a number is a composite (not a prime.)

If the test is positive, the number is guaranteed to be a composite, otherwise, it might be a prime.

However, statistically speaking, this method is good enough for many practical applications, including encryption--RSA in particular.

There are 1,091,987,405 primes less than 25,000,000,000; but only 21,853 pseudo-primes base two, which gives us an error probability less than 0.00009% (a very miniscule probability of error -- and we can live with that!).

Note that the term pseudo-prime refers to the result of the primality test to be a positive test (not necessarily that it is a prime. See the primality test above.

We can reduce this margin of error even further by using multiple bases. This is exactly what the Miller-Rabin method does. See next function illustration for the Miller-Rabin Primality Test below.

The Miller-Rabin primality test method gives us a proved probability of error less than 1/s2, where s is the number of bases we tried.

The following code illustration uses a built-in PHP function called gmp_prob_prime() to test the number for primality.

Behind the scene, function gmp_prob_prime() uses Miller-Rabin algorithm to return primality test result.

<?php
$max = 2147483647;
   
$primeFound = 0;
$probablePrime = 0;

for ($x = 1; $x <= $max; $x++)
    {
     $primeStatus = gmp_prob_prime($x);

     if ($primeStatus == 1)
        {
         $probablePrime++;
        }
     else if ($primeStatus == 2)
        {
         $primeFound++;
        }
    }
echo "Total primes found between 1 and " . $max;
echo " - certain primes found: " . $primeFound;
echo "probable primes: " . $probablePrime;
?>

Based on that the following results were obtained:

Total primes found between 1 and $max - certain primes found:

1 - 100000      - certain primes found: 9592,     probable primes: 0

Total primes found between 1 and $max is:

1 - 1000000     - certain primes found: 78498,    probable primes: 0

Total primes found between 1 and $max is:

1 - 10000000    - certain primes found: 78498,    probable primes: 586081

Total primes found between 1 and $max is:

1 - 100000000   - certain primes found: 78498,    probable primes: 5682957

Total primes found between 1 and $max is:

1 - 1000000000  - certain primes found: 78498,    probable primes: 50769036

Total primes found between 1 and $max is:

1 - 2147483647  - certain primes found: 78498,    probable primes: 105019067

Don't worry if you don't understand the code above! It's not that important!
It's for illustration purpose only!

Instead, check out PHP documentation on gmp_prob_prime()
?>

Let's focus our attention in finding and factoring primes.

Factoring Primes

The dual problems of factoring integers and testing primality have surprisingly many applications for a problem long suspected of being only of mathematical interest.

As we'll see below, the security of the RSA public-key cryptograph system is based on the computational intractability of factoring large integers [i.e., (p - 1)(q - 1)].

Before we go on, I want to clarify one term that is being used throughout this tutorial and in other texts describing the RSA cryptography. That term is: factoring or factorize or plainly as factor.

What does it mean?

Well, in mathematics, to factor a number is to derive or break that number into small chunks so that the chunks still retain the original property or meaning.

For example, how many smaller chunks can 6 be broken into?

How many factors can 6 be factored?

Well, let's see the possibilities: 6/6 = 1, 6/1 = 6, 6/2 = 3, 6/3 = 2. Answer: 4 or 4 factors.

Notice that 6/4 = 1.5 and 6/5 = 1.2 are not factorizable.

You'll see later that we multiply two prime numbers (p - 1)(q - 1) to create a public key.

For example: (3 - 1)(5 - 1) = 8

Now 8 is the result of the factorization of (p - 1)(q - 1)

Note: 8 is not the factor of (p - 1)(q - 1). It is the result of factoring (p - 1)(q - 1)

.

So that's what the term: factoring or factorize or factorization or plainly as factor means.

Now let's continue on from where we left off:

[A side note: As a more modest application, hash table performance typically improves when the table size is a prime number.

To get this benefit, an initialization function must identity a prime near the desired table size.]

As you imagine, factoring and primality testing are related problems. However, they are quite different algorithmically.

In the sections above, we saw that we can demonstrate that an integer is composite (i.e., not prime) without actually giving the factors.

To convince yourself of the plausibility of this, note that you can demonstrate the compositeness of any nontrivial integer whose last digit is 0, 2, 4, 5, 6, or 8 without doing the actual division.

The simplest solution to factorization is also the simplest one used in primality tests; that is, brute-force trial-division.

However, this is extremely slow for big numbers, and, therefore, impractical for any real application.

Another solution, a bit faster than trial-division, is the Square Root Method. See an illustration later.

The Square Root Method is okay for small numbers (15 digits or less), but will become too slow for anything larger than that.

[Note: For heavy-duty industrial commercial encryption purposes, anything less than 150 digits is considered small.]

The Square Root Method as the name implies used square root to implement the function.

The fastest known algorithm used in factorization is the Number Field Sieve. It uses randomness to construct a system of congruences, the solution of which usually gives a factor of the integer.

The method was developed by Pollard and was used to factor the RSA-130 number (such a feat required enormous amounts of computation power.)

As you can see, the strength of encryption algorithms such as RSA relies on the fact that it's really hard to decompose a large number into its factors.

These algorithms use an integer n made of two or more primes, such as: n = p x q or n = p x q x r x s where p, q, r, and s are large prime numbers.

Breaking n into its factors requires an enormous amount of computation that can last for many years (even when using multiple machines).

To demonstrate how secure such algorithms can be, cash prizes were offered to those who manage to factorize these numbers.

Message Encryption

This huge disparity between the ease of finding large prime numbers, and the difficulty of factoring large numbers, is fully exploited when devising secure forms of public key cipher systems.

In other words, finding large prime numbers is very easy, but factoring them is very hard.

The basic components of the system are two programs, an encryptor and a decryptor.

Both the sender/encryptor and receiver/decryptor need to have keys.

Typically, the keys will consist of one hundred or more digits -- a very large number. The security of the system depends on keeping some of the keys secret.

This method immediately raises the following question: How can we send the key to the receiver of our message?

If we decide to mail it through a postal mailing system, we need to trust that the mailing system is absolutely 100% secured and tampered proof. Can we trust that? If we send a food recipe to our family and relatives, there is no problem in sending the key through the mailing system.

Or we can always meet up with the person and hand the key to that person days, months, or years in advance and let that person use that key to send us encrypted materials whenever that person needs to do so.

Yeah, we can do that, but it's not very practical for other uses, say, when you want to send a sensitive document to a person far, far away in the other side of the world.

To solve this problem, Whitfield Diffie and Martin Hellman, in 1975, proposed the idea of a public key cryptosystem (PKS).

In a PKS, each potential message receiver A (which would be anyone who intends to use the system) uses a program that will produce not one, but two keys: An encryption key and a decryption key.

The encryption key is made public to all those interested in sending "the receiver" A a message, while the decryption key is kept secret.

Although the basic idea behind such a system is simple, designing it is not.

The one originally proposed by Diffie and Hellman turned out to be not as secure as they had thought, but a method devised a short time later by Rivest, Shamir, and Adleman (the RSA fame) proved to be much more robust and secure, and its byproduct, the RSA system, is now being used widely in international banking, online transactions, military and satellite communications, to name just a few.

The main difficulty for anyone designing such a system is that the encryption process should disguise the message to such an extent that it is impossible to decode it without the decryption key.

But because the essence of the system, and indeed of any cipher system, is that the authorized receiver can decrypt the encoded message, the two keys must be mathematically related.

The receiver's program and decryption key should exactly undo the effect of the sender's program and encryption key, so it should be theoretically possible to obtain the decryption key from the encryption key, provided one knows how the cipher programs work.

The trick is to ensure that, although it is theoretically possible to recover the decryption key from the publicly available encryption key, it is practically impossible.

Let's put it this way: To break the encryption, all you have to do is undoing or unraveling the public key that is publicly made available to anyone, including hackers. In other words, break the public key into its factors of p * q.

In mathematic, undoing the product of p * q means to do a multiplicative inverse of p * q.

So to break the public key, all you have to do is performing a multiplicative inverse of p * q.

This is how hackers break encryption by using computer programs to calculate the multiplicative inverse of the public key.

The public key = p * q

Or it is usually written as n = p * q.

To undo or break the public key, all you have to do is factoring the public key (or n) into its possible factors which is practically impossible if you use large prime numbers.

In the case of one-way ciphers such as RSA, the receiver's secret decryption key consists of two large prime numbers (p and q at least 75 digits each), and the public key consists of their product (a 150-digit number = 75 + 75).

With current technology, it's practically impossible to factor numbers of that size in a reasonable time.

In computer memory, each digit holds 16 bits. So when working with cryptography, you use numbers that are multiples of 16 or divisible by 16. For example, a 1024-bit and 2048-bit keys are divisible by 16.

In general, if you're working with numbers of size N bits, you'll need 2*N bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need 1024 * 2 / 16 = 128 digits of storage.

Let's for the sake of simplicity, we use two primes: 2 and 3, and, therefore, the public key becomes 6.

Now all we have to do to unravel the public key is to factor the public key, which is 6, into its original two primes: 2 and 3.

We can do it in our head with these small primes, and even with numbers reasonably large, hackers can still use computer programs to factor these public keys to unravel the public keys.

A computer can quickly compute the greatest common divisor of two numbers using the Euclidean algorithm, so an attacker can run the algorithm on two public keys. If their greatest common divisor is not 1, then the attacker has found a prime number dividing both keys, therefore breaking two keys at the same time.

For example, suppose two public keys were 239149 and 166381. It is difficult to factor either of these two numbers by hand, but the Euclidean algorithm can be done by hand, revealing that the two numbers have a greatest common divisor of 379.

To give you a quick idea of the importance of this algorithm, here are a few of the security protocols that currently implement RSA.

  • IPSEC/IKE - IP data security.

  • TLS/SSL - Transport data security (Web).

  • PGP - Email security.

  • SSH - Terminal connection security.

  • SILC - Conferencing service security.

  • and many others.

As I mentioned in the previous section, efforts to develop new algorithms to factorize such numbers are usually subjects for doctorate theses and can bring instant fame for those who succeed.

The current record for factorization is around 155 digits.

(Note: New algorithms designed for quantum computers, when and if they ever get to build one, may render this sort of encryption system obsolete, but until then, RSA will continue to be one of the safest encryption systems available.)

The RSA Algorithm

To create a good implementation of the RSA algorithm, you need three things:

  1. Arbitrary precision arithmetics (multiple precision arithmetic functions). See precision arithmetic functions later.

  2. A pseudo-random number generator to use to generate random primes.

    It is generallly a typical practice to create primes using some random methods (i.e., rand()) to generate a random number and then test for prime, rather than just picking some numbers and test for primes. See earlier sections on how to generate primes, especially function findPrimeRange().

    Also, be mindful of the "computationally intensive" problem when selecting a range of number to use in findPrimeRange().

    Check this out as well to find the next prime number say, if want to find the next prime number after 10, gmp_nextprime(10) will return 11. This PHP function is suiteable for looking for a certain prime number after a certain number, say, you want to find a prime number after 25436.


  3. A knowledge on how to use Euclidean Arithmetic to solve the Greatest Common Divisor of two numbers, especially finding the inverse of a number and taking a modulo on another number.

    More on this topic later.


With the facts presented up to this point, we can now start a formal description of the algorithm behind RSA.

The best way to describe it is using the simplest case possible: Where a sender, call it S, wants to send a message to a receiver, call it R.

For the particular case of this example, we will assume that the message is a two-digit integer. For example, 77.

Before it can receive secure messages from S or anyone else interested in sending messages, R will need to generate a public key.

To do this, R must find two large prime numbers, call them p and q, having at least 75 digits, then multiply them to make a number n such as n = p.q.

PHP has a function called bcmul() that multiplies two arbitrary precision numbers p and q. So n = bcmul(p, q).

n will be R's public key (and R should keep p and q a secret).

Somewhere in your coding process, you need to handle the keys gracefully, such as store them in a database or file or some secure medium, while at the same time, making sure that they can be easy access to them so that you can retrieve them quickly and use them.

If you choose to store them in a file, PHP has two functions to make storing/retrieving very easy. These functions are called file_put_contents() and file_get_contents().

// reading/retrieving keys from config file containing keys

$config = json_decode(file_get_contents('http://www.example.com/config/config.json'));

$key_expiration_date = $config['key']['KEY_EXPIRE'];

$login_expiration_date = $config['login']['LOGIN_EXPIRE'];

foreach ($config as $k => $v)
      {
       if ($k == 'key')
          {
           // test for certain expiration date and handle it accordingly
           // you might find a more elegant way of comparing the two dates than this!
           // you get the point!
           if ($key_expiration_date > 'today's date')
              {
               // the expiration date has not been reached ... keys are still good!
               // proceed on!

               foreach ($v as $key => $value)
                     {
                      if ($key == 'P')
                         {
                          $p = $value;
                         }
                      elseif ($key == 'Q')
                         {
                          $q = $value;
                         }
                      elseif ($key == 'PUBLIC')
                         {
                          $public_key = $value;
                         }
                      elseif ($key == 'PRIVATE')
                         {
                          $secret_key = $value;
                         }
                     } // end inner foreach ($v as $key => $value)
              } // end if ($key_expiration_date > 'today's date')
           else
              {
               // keys have expired .... discard old keys and generate new keys!
               // and update your json file to reflect your changes!
              }
          } // end if ($key == 'key')
       elseif ($k == 'login')
          {
           // test for certain login expiration date and handle it accordingly
           // you might find a more elegant way of comparing the two dates than this!
           // you get the point!
           if ($login_expiration_date > 'today's date')
              {
               // the login expiration date has not been reached ... keys are still good!

               // handle login accordingly
              }
           else
              {
               // login keys have expired .... discard old keys and generate new keys!
               // and update your json file to reflect your changes!
              }
          } // end elseif ($k == 'login')
      } // end outer foreach ($config as $k => $v)

storing keys in the config file

this code below is incomplete due to space constraint.
please check out my other tutorial call "Introduction to Ajax" and navigate
to the very end of that tutorial to find example code similar to the one below.

$config = .......

file_put_contents('http://www.example.com/config/config.json',
json_encode($config, JSON_PRETTY_PRINT));

keys must be encrypted, especially the private key.
there are several pure PHP implementations of the symetry
algorithms on the Web that you can use to encrypt your keys, 
such as RC4, AES, DES3, Blowfish, etc.

the process goes like this:

generate two primes and solve for d and then encrypt them and
store them.

when you need to use them, retrieve them and decrypt them and
use them.

there is a pure PHP implementation of the symetry algorithm
RC4 in my other tutorial called "Introduction to RC4."

now a json config.json file looks like this:

{
    "key":
          {
           "P": "1e8f50c3a80b7c0",
           "Q": "4a01fb7c0e92b6c",
           "D": "0f0c1b3c0e5a218",
           "E": "6a9e1f3c0e98b6c",
           "PUBLIC": "e201ab3c39c7d4e1d",
           "PRIVATE": "0f5b3c390g3d20b3c",
           "KEY_EXPIRE": "2592000"
          },

    "login":
          {
           "USERNAME": "my_username",
           "PASSWORD": "7ac1f1b7c0e92b6f",
           "LOGIN_EXPIRE": "2592000"
          }
}

note: do not embedd any comment in your json file!

basically, once you've retrieve this json file,
you can convert it into an array using json_decode() so that
you can iterate through your array as you normally would!

one last note:

it is a good idea to tie your keys to an expiration date,
so that you can discard them and issue new keys.
this practice adds extra security to your security system.

you can timestamp your key file and read the timestamp
of that file and compare it against the current timestamp.

for example, a value for a 24-hour timestamp is: 3600 * 24 * 30
or 2,592,000 miliseconds.

PHP's current timestamp function is: time()

$time is 24 hours old, it's 24 hours ago, it's yesterday!
$time = time() - (3600 * 24 * 30);

if your file time was created two days, filemtime() should
be less than $time. confusing?

check out PHP doc for filemtime()

filemtime() returns Unix timestamp in milliseconds: '20452718039105'
for example:
$filemtime = filemtime('http://www.example.com/config/config.json')

if ($filemtime < $time)
   {
    // expired
    // do something!
   }

how you implement such system is up to you!

the example shown here is not the only way to do it!

Besides the generation of the public key, R should agree with S on a method to encode the actual message text.

Now let's break the process of encrypting and decrypting the message into steps:

  1. R needs to select two primes (see previous sections on finding primes, particularly function findPrimeRange()). Here, we'll use p = 17 and q = 31, for example.

    Note that p and q must be kept secret.

    But keep in mind that in real applications, this number must be at least 75 digits, depending on how secure you want your message to be.

    As a rule of thumb, use a somewhat small number for your "not so important" message so that you don't consume too much processing power.

    You increase the number accordingly as your message gets more sensitive.

    That's why maintaining a storage device, i.e., file or database, for storing different levels of security is very crucial.

  2. R now generates n by multiplying p and q. Such as n = 17 x 31; that is n = 527.

    527 will be R's public key.

  3. R now must calculate phi, which denoted by a Greek letter ϕ.

    ϕ = (p - 1)(q - 1).

    phi = (p - 1)(q - 1), which is 16 x 30 or 480.

  4. R now chooses another number called it e which must meet these two conditions:


    1. e must be between 1 and phi or 480.

    2. e also must be a relative prime to phi or 480.


    Remember the definition of relative prime?

    To refresh your memory: A prime number is considered a relative prime to any other number if it (prime) does not divide that number. Another way of saying is that, choose a number e that is not divisible by the prime.

    So e cannot divide 480. Or 480 is not divisible by e.

    By the definition of relative prime, we know that the following numbers cannot divide 480: 7, 11, 13, 14, etc.

    And 7, 11, 13, 14,.... must be between 1 and 480, so they all satisfy both conditions for step 4.

    Notice that 14 is an even number and yet it does not divide 480. So it satisfies the definition.

    Also notice that e doesn't need to be an odd number (as the even number 14 shows).

    Now in real life (application) the hard part is finding e, especially if you're not math-inclined and especially when numbers must be very large as is the case when you program real RSA cryptography applications.

    Basically, finding e comes down to finding a number e such as the Greatest Common Divisor (or GCD) between e and 480 is 1.

    In other words, it's this equation: GCD(e, 480) = 1.

    But not this equation: GCD(e, 480) = 0.

    In practice, e is often chosen to be 216 + 1 = 655372, though it can be as small as 3 in some cases. In other words, do not choose e higher than 655372.

    If your phi is larger than 655372, choose e between 3 and 655372 but no higher than 655372.

    e will be the other half of the public key (and n is the other half).

    Basically, the Greatest Common Divisor of two integers A and B is the largest integer that divides both A and B.

    In other words, the Greatest Common Divisor of two integers e and 480 is the largest integer that divides both e and 480.

    The Euclidean Algorithm is a technique for quickly finding the GCD of two integers.

    PHP has a function to solve GCD. Check this out: Find the Greatest Common Divisor of two integers

    Once you solve this equation: GCD(e, 480) = 1 using the Euclidean Algorithm to quickly find the GCD of two integers, then that is your number e for your step 4.

    Please check out tutorials for the subject of Greatest Common Divisor on the Web, particularly on YouTube. It will make you a better RSA cryptosystem programmer.

    Here are two of them:

    The Extended Euclidean Algorithm to find the GCD of two integers The Extended Euclidean Algorithm to find the Modular Inverse of a number: How To Find The Inverse of a Number ( mod n ) - Inverses of Modular Arithmetic

    In mathematic, an inverse of a number, n, is written as n-1 or 1/n.

    Knowing that, we can use the Euclidean Algorithm to quickly solve the inverse of a number, say, 27, and then take a modulo of another number, say, 392.

    Likewise, we can solve the inverse of a number, say, 11, and then take a modulo of another number, say, 480.

    Later, I will show you how to calculate Euclidean Algorithm to find GCD(A, B) = 1.

    For now let's forge on the rest of the description of the RSA algorithm.

    If you look at the very beginning of this step 4, it says R needs to choose a number e. You can choose any number between 1 and 480 that does not divide 480 and it will work out just fine.

    This is very easy using function findPrimeRange(1, 480) to list prime numbers between 1 and 480.

    How you pick out a particular prime number from function findPrimeRange() is up to you.

    However, it is very easy to do, for example, assuming prime holds the array of prime range generated by function findPrimeRange() [i.e., prime = findPrimeRange(1, 480)], you can easily pick out the array index: prime[3], prime[38], or prime[115], etc.

    Let's do that now from the list: 7, 11, 13, 14, etc.

    [Note: findPrimeRange() starts with prime[0] = 2, prime[1] = 3, prime[2] = 5, prime[3] = 7, prime[4] = 11]

    Let's pick e = 11 for this example (or more specifically prime[4] = 11]).

    The number e (11 in this case) is also part of the public key, and, therefore, R will have to make it public together with n.

    Make note: e and n are public keys. R can give both e and n to anyone that wants to send R messages.

    So step 4 looks like this: GCD(11, 480) = 1

  5. With the knowledge of n and e, the sender S can now prepare to send the message to R.

    Let's call this message M.

    It is necessary to convert the message M into a number because the RSA uses numbers to calculate the algorithm. One common conversion process uses the ASCII alphabet.

    For this example, the message in our case is a single two-digit number. For example: M = 77. The ASCII code for M is 77.

    It could be a file containing pages of texts, i.e.:

    THE RED COATS ARE COMING! THE RED COATS ARE COMING! THE RED COATS ARE COMING! ....

    T = 84, H = 72, E = 69, a space = 32, R = 82, E = 69, D = 68, C = 67, O = 79, A = 65, T = 84, S = 83, a space = 32, A = 65, R = 82, E = 69, a space = 32, C = 67, O = 79, M = 77, I = 73, N = 78, G = 71, ! = 33.

    For more see Extended ASCII Code

    For example, the message (M) THE RED COATS ARE COMING! would be encoded as 847269328269686779658483326582693267797773787133.

    As you can see, that is an anormous large number. It is important that M < n, as otherwise the message will be lost when taken modulo n. In other words, the number 847269328269686779658483326582693267797773787133 raise to any power will be too computationally intensive and the computer will go haywire on you.

    So if n is smaller than the message, as is often the case, it will be sent in pieces. In our example, n = 527, but our M is 77.

    So it seems that we don't need to send the message character by character.

    Now with n = 527 and M is 77, what else can we send? Not many characters. Try 'Me' = 7769. That is over 527.

    So no need to worry about M < n in this case. We'll send M as a single character.

    Make note: If n is smaller than M, then S will have to send the message character by character (as our example M = 77 shows).

    If you have a long string like THE RED COATS ARE COMING!, send it one character at a time using our example (M = 77) as a guide.

    Use loop(s) to loop through the encryption process, encrypting one character at a time.

    Likewise, on the decryption side, use loop(s) to loop through the decryption process, decrypting one character at a time.

    Later, as a bonus material, I probably will show you a secret of sending long strings like THE RED COATS ARE COMING! broken into smaller pieces (if I have time) by using loops to convert ASCII characters to its ordinal number and back to its original ASCII character.

    Other alternatives are to use one of the symetry encryptions like AES (Advanced Encryption Standard), DES (Data Encryption Standard), IDEA (International Data Encryption Algorithm), Blowfish (Drop-in replacement for DES or IDEA), RC4 (Rivest Cipher 4), RC5 (Rivest Cipher 5), RC6 (Rivest Cipher 6), etc.

    I recommend using RC4 because it is fast and simple to use and millions of people, industries, and organizations have been using it for decades to send secure large documents. See my tutorial on RC4.

    As for AES, DES, and IDEA are too overkilled for the majority of us who don't need military-grade encryption. Blowfish is also a little overkilled for the majority of our encryption tasks.

    As for RC5 and RC6 are proprietary algorithms and you need to obtain permission from RSA Security to use them. That left us the RC4 as the best alternative to use.

    So if you need military-grade encryption, use RSA encryption algorithm described in this tutorial, and for non-military-grade encryption, use RC4.

  6. S now encrypts the message by appplying a sequence of mathematical operations over M that will result in the encrypted message C:


    C = M e