Skip to content

Instantly share code, notes, and snippets.

@jasonherndon
Last active June 21, 2017 01:52
Show Gist options
  • Save jasonherndon/9ee641edfaf2e25fd71b83861b4e539a to your computer and use it in GitHub Desktop.
Save jasonherndon/9ee641edfaf2e25fd71b83861b4e539a to your computer and use it in GitHub Desktop.
How we calculate change on the trade
/*
*
* HEY KEVIN!
*
* OKAY .... SO HERE's HOW TO READ THIS SO YOU CAN CHECK MY LOGIC
* I HAVE TO ALWAYS TRANSLATE OUR EXPLAINATIONS INTO CODE
* AND THEN I HAVE TO ACCOUNT FOR DATA THAT MAY/MAY NOT BE THERE
* SO HERE'S WHERE YOUR LAST EMAIL ENDED UP...
*
* TO READ THIS:
* CONSIDER: $this = "a given property"
* AND "//" is a comment ... the rest is the live code
*
*/
// Let's set some initial values ... we'll override these later
$change = [
'amount' => 0,
'percentage' => 0,
'positive' => true,
];
/*
First, let's find a starting value for a given property
*/
// Get yesterday's last trading value value
$yesterdaysLastTrade = $this->yesterdaysTrades->last();
// IF there was a trade yesterday,
if ($yesterdaysLastTrade)
{
// Get it's price and use it as today's starting value
$todaysStartingValue = $yesterdaysLastTrade->price_per_share;
// IF there was no trade yesterday
} else {
// Get the last price that it traded at before yesterday
$lastKnownPriceBeforeToday = $this->allTradesBeforeYesterday->last();
// If we find a known price before today
if ($lastKnownPriceBeforeToday)
{
// Use it as starting value
$todaysStartingValue = $lastKnownPriceBeforeToday->price_per_share;
// But if we don't find a last known price (i.e., it's never traded)
} else {
// use the initial trade value from the admin panel
$todaysStartingValue = $this->masterInfo->initial_trade_value;
}
}
/*
Now that we have a starting value, let's see if there's been any trades today
*/
// Get today's trade
$todaysTrade = $this->todaysTrades->last();
// If there was a trade today
if (count($todaysTrade) > 0)
{
// Okay, now that we have a starting value... and a trade for today ... we can begin to do some maths
$amountOfChange = $todaysTrade->price_per_share - $todaysStartingValue;
// If the change is positive, it will be an integer greater than or equal to 0
// this will make sure to tell it to be red or green
if ( (int)$amountOfChange == $amountOfChange && (int)$amountOfChange >= 0 )
{
$change['positive'] = true;
} else {
$change['positive'] = false;
}
// Format the response ... first the amount
$change['amount'] = $amountOfChange;
// then we get it as a percent where amount of change times 100 is divided by the starting value
$changeAsPercent = (int)$amountOfChange * 100 / $todaysStartingValue;
// then round it to a whole percent
$change['percentage'] = (int)number_format($changeAsPercent,0);
// Else if there hasn't been any trades today, the change is zero
} else {
// so we do nothing
}
// Return the change information
return $change;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment