I want to make a function for my ICO to calculate ethers collected so far and convert them into USDollars. I wanted to hard cap my ICO in USDollars. Is it possible to do so ? I am using Solidity to create my ICO smart contract
You need to use an Oracle to get the price conversion onto the blockchain.
If you want to initiate your own Oracle based smart contract, you should look at the developer docs for Oraclize.it. They have an example for just this scenario:
JSON Parsing: To extract the last-price field from the Kraken API, the fist parameter of the query
However, it might be better and more cost effective for you to take advantage of another smart contract which has already set up an oracle to get and store this data.
I can't really recommend one that I have personally used, but I believe the general consensus is that MakerDAO has a bunch of oracles set up for their own services that you should be able to use.
Edit: Check out MakerDAO
If you want to get financial data, and don't want to wait a block (or more) and pay GAS and then ETH fees with something like Oraclize, you can get stock, crypto, ETF, etc data from the OrFeed.org's smart contract for free and instantly from your smart contract.
For realtime prices from Dexes like Kyber and Uniswap:
uint price = orfeed.getExchangeRate("ETH", "USDC", "SELL-UNISWAP-EXCHANGE", 10000000000000000);
All the 0s are because the tokens have so many 0s (18 usually).
uint price = orfeed.getExchangeRate("BTC", "DAI", "SELL-KYBER-EXCHANGE", 100);
For Forex data from Synthetix:
uint price = orfeed.getExchangeRate("JPY", "USD", "DEFAULT", 100000);
Stock (more centralised but becoming less so):
uint price = orfeed.getExchangeRate("AAPL", "USD", "PROVIDER1", 1);
Docs on on the site and github.
Hope this info is useful!
Disclaimer: I contribute to the Orfeed project.
You don't need to use Oraclize.
Just get the price with
curl from this URL https://min-api.cryptocompare.com/data/pricemulti?fsyms=ETH&tsyms=USD
and send a transaction to your contract update the price storing it in some variable. It is going to be much cheaper this way.