function crsi_buy($date, $breakOutSignal, $ADX_filter, $breakOutOrderBy, $portfolioID, $dailyBuyList, $enterCRSI, $enterRange, $enterLimit, $tranHistory, $orderBy, $next_date, $skipFactor, $stop_loss_multiplier, $max_risk, $risk_factor) { global $max_num_holdings; #global $max_risk; #global $risk_factor; #global $stop_loss_multiplier; global $portfolio_tbl; global $showOutput; global $commission; global $tranHistArray; global $portfolio_table; if (!$portfolioID) { $portfolioID = 1; } if (!$dailyBuyList) { $dailyBuyList = "crsi_daily_buy_list"; } $breakOutStockArray = getBuyList($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit, $orderBy); $sizeBuyList = sizeof($breakOutStockArray); if (!$skipFactor) { $skipFactor = 0.05; } /* echo "date: $date ", PHP_EOL; $count = sizeof($breakOutStockArray); echo "len array: $count ", PHP_EOL; for ($y=0; $y<sizeof($breakOutStockArray); $y++) { echo "symbol: ", $breakOutStockArray[$y]['symbol'], PHP_EOL; } echo " end end ", PHP_EOL; */ $len_array = count($breakOutStockArray); //$risk_factor = 1 / $max_num_holdings; $portfolio_value = 0; $current_pos = 0; $next_buy_point = 100000; $stop_loss = 0; $num_shares = 0; $current_N = 0; $risk_value = 0; $purchase_value = 0; $sim_start_day = 55; $pyramid_mode = 0; $stop_loss = 0; $current_trade_date_id = 0; $workingArray = $breakOutStockArray; $adxArray = ""; $adxCount = 1; $len_array = count($breakOutStockArray); $portfolio_value = get_historical_turtle_portfolio_value($date, $portfolioID); $query = "select shares from {$portfolio_table} where symbol = 'CASH' and portfolio_id = " . $portfolioID; $result = queryMysql($query); while ($data = mysql_fetch_row($result)) { $cash = $data[0]; } #echo "date: $date symbol: ", $breakOutStockArray[$x]['symbol'], "cash: $cash purchase value: $purchase_value current risk: $current_risk max risk: $max_risk ", PHP_EOL; $current_risk = get_portfolio_risk($date, $portfolioID); #echo "date: $date symbol: ", $breakOutStockArray[$x]['symbol'], "cash: $cash purchase value: $purchase_value current risk: $current_risk max risk: $max_risk ", PHP_EOL; #print "current risk in the beginning: $current_risk \n"; $buy_array = array(); $skipNum = ceil($skipFactor * $sizeBuyList); #echo "date: ", $date, " size: ", $sizeBuyList, " skipping: ", $skipNum, PHP_EOL; #for ($x=1; $x < $len_array; $x++) { for ($x = $skipNum; $x < $sizeBuyList; $x++) { ### get portfolio value #$portfolio_value = get_historical_turtle_portfolio_value($date, $portfolioID); ### get current available cash #$query = "select shares from turtle_portfolio where symbol = 'CASH' and portfolio_id = ".$portfolioID; #$result = queryMysql($query); #while ($data = mysql_fetch_row($result)) { # $cash = $data[0]; #} $risk_value = $portfolio_value * $risk_factor / 100; $current_N = $breakOutStockArray[$x]['ATR']; if ($current_N > 0) { $num_shares = floor($risk_value / ($stop_loss_multiplier * $current_N)); } /* $purchase_value = $num_shares * $breakOutStockArray[$x][$breakOutSignal]; $stop_loss = $breakOutStockArray[$x][$breakOutSignal] - (2*$current_N); $stop_buy = $breakOutStockArray[$x][$breakOutSignal] + $current_N; */ #echo "x: $x date: $date portfolio value: $portfolio_value cash: $cash risk value: $risk_value current N: $current_N symbol: ".$breakOutStockArray[$x]['symbol'], PHP_EOL; ## set purchase price to next day open price $breakOutStockArray[$x]['purchase_price'] = getStockPrice($next_date, $breakOutStockArray[$x]['symbol'], 'open'); if (!$breakOutStockArray[$x]['purchase_price']) { break; } $h = $breakOutStockArray[$x]['high']; $l = $breakOutStockArray[$x]['low']; $o = $breakOutStockArray[$x]['open']; $c = $breakOutStockArray[$x]['close']; $p = $breakOutStockArray[$x]['purchase_price']; #print "trade date: $date symbol $s close: $c open: $o purchase price = $p <br /> \n"; #$breakOutStockArray[$x]['purchase_price'] = $breakOutStockArray[$x]['buy_price']; $purchase_value = $num_shares * $breakOutStockArray[$x]['purchase_price'] + $commission; $stop_loss = $breakOutStockArray[$x]['purchase_price'] - $stop_loss_multiplier * $current_N; $stop_buy = $breakOutStockArray[$x]['purchase_price'] + $current_N; #$current_risk = get_current_risk($portfolioID); #$current_risk = get_portfolio_risk($date, $portfolioID); #print "date: $date symbol: ".$breakOutStockArray[$x]['symbol']." current risk :$current_risk \n"; #echo "date: $date symbol: ", $breakOutStockArray[$x]['symbol'], "cash: $cash purchase value: $purchase_value current risk: $current_risk max risk: $max_risk ", PHP_EOL; if ($cash > $purchase_value && $current_risk < $max_risk) { $cash = $cash - $purchase_value; $risk_dollar = $num_shares * ($stop_loss_multiplier * $current_N); $risk_pct = $risk_dollar / $portfolio_value * 100; // insert into turtle_portfolio $my_sql = "insert into {$portfolio_table} (portfolio_id, symbol, last_price, shares, cost_basis, stop_loss, stop_buy, risk, risk_pct) "; $my_sql .= "values (" . $portfolioID . ", '" . $breakOutStockArray[$x]['symbol'] . "', "; $my_sql .= $breakOutStockArray[$x]['adj_close'] . ", "; $my_sql .= $num_shares . ", "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $stop_loss . ", "; $my_sql .= $stop_buy . ", "; $my_sql .= $risk_dollar . ", "; $my_sql .= $risk_pct . " )"; array_push($buy_array, $my_sql); $current_risk += $risk_pct; #print "current risk after adding risk dollar: current risk: $current_risk risk pct added: $risk_pct max risk: $max_risk \n"; #$showOutput = true; if ($showOutput) { print "num: {$x} sql: {$my_sql} <br />"; $p = $breakOutStockArray[$x]['purchase_price']; print "cash: {$cash} purchase price: {$purchase_value} num shares: {$num_shares} purchase value: {$p} current n: {$current_N}<br />"; } #$result = queryMysql($my_sql); // trigger on transaction table /* DELIMITER $$ CREATE TRIGGER ins_buy AFTER INSERT ON turtle_portfolio_transaction FOR EACH ROW BEGIN DECLARE xid int; IF (NEW.trade_type = 'BUY') THEN insert IGNORE into open_buy_transaction (portfolio_id, symbol, trade_type, trade_date, shares, price) values (NEW.portfolio_id, NEW.symbol, NEW.trade_type, NEW.trade_date, NEW.shares, NEW.price); ELSE insert IGNORE into transactions (portfolio_id, symbol, sell_date, sell_shares, sell_price) values (NEW.portfolio_id, NEW.symbol, NEW.trade_date, NEW.shares, NEW.price); SET xid = select 1 from transactions; update transactions, open_buy_transaction set transactions.buy_date = open_buy_transaction.trade_date, transactions.buy_shares = open_buy_transaction.shares, transactions.buy_price=open_buy_transaction.price where transactions.symbol = open_buy_transaction and transactions.xid = xid ; delete from open_buy_transaction where symbol = NEW.symbol END IF; END; $$ DELIMITER ; */ // insert into transaction history table $my_sql = "insert into {$tranHistory} (portfolio_id, symbol, trade_type, trade_date, shares, price, risk, risk_pct, vsSpyRank) "; $my_sql .= "values (" . $portfolioID . ", '" . $breakOutStockArray[$x]['symbol'] . "', "; $my_sql .= "'BUY', "; $my_sql .= "'" . $date . "', "; $my_sql .= $num_shares . ", "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $risk_dollar . ", "; $my_sql .= $risk_pct . ", "; $my_sql .= $breakOutStockArray[$x]['vsSpyRank'] . " )"; array_push($tranHistArray, $my_sql); if ($showOutput) { print "{$my_sql} <br />"; } #try { # $result = queryMysql($my_sql); #} catch (Exception $e) { # echo "query: $my_sql \n"; # echo 'Caught exception: ', $e->getMessage(), "\n"; #} // update cash position #$my_sql = "update turtle_portfolio set shares = ".$cash." where symbol = 'CASH' and portfolio_id = ".$portfolioID; #$result = queryMysql($my_sql); } else { #print "trade date: $date ran out of money </ br> \n"; break; } $pyramid_mode++; } $my_sql = "update {$portfolio_table} set shares = " . $cash . " where symbol = 'CASH' and portfolio_id = " . $portfolioID; $result = queryMysql($my_sql); foreach ($buy_array as $buy) { try { queryMysql($buy); } catch (Exception $e) { echo "Query: {$buy} \n"; echo 'Caught exception: ', $e->getMessage(), "\n"; } } populateDailyBuyList($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit); }
function crsi_buy($date, $breakOutSignal, $ADX_filter, $breakOutOrderBy, $portfolioID, $dailyBuyList, $enterCRSI, $enterRange, $enterLimit, $tranHistory, $orderBy, $next_date) { global $max_num_holdings; global $max_risk; global $risk_factor; global $stop_loss_muptiplier; global $portfolio_tbl; global $showOutput; if (!$portfolioID) { $portfolioID = 1; } if (!$dailyBuyList) { $dailyBuyList = "crsi_daily_buy_list"; } //$breakOutSignal = "55_DAY_HIGH"; ### get list of breakout stocks //$breakOutStockArray = array(); #$crsiThreshold = 20; #$pctLimitBelow = 2; #$enterCRSI = 20; #$enterRange = 100; #$enterLimit = 2; // $breakOutStockArray = getBreakoutStock5 ($date, $breakOutSignal, $breakOutOrderBy, $portfolioID, $dailyBuyList); // $breakOutStockArray = getBreakoutStock6 ($date, $breakOutSignal, $breakOutOrderBy, $portfolioID, $dailyBuyList); $breakOutStockArray = getBuyList($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit, $orderBy); // echo json_decode($breakOutStockArray); // set how many breakout stocks to buy //$len_array = count($breakOutStockArray); $len_array = count($breakOutStockArray); $risk_factor = 1 / $max_num_holdings; $portfolio_value = 0; $current_pos = 0; $next_buy_point = 100000; $stop_loss = 0; $num_shares = 0; $current_N = 0; $risk_value = 0; $purchase_value = 0; $sim_start_day = 55; $pyramid_mode = 0; $stop_loss = 0; $current_trade_date_id = 0; $workingArray = $breakOutStockArray; $adxArray = ""; $adxCount = 1; $len_array = count($breakOutStockArray); for ($x = 1; $x < $len_array; $x++) { ### get portfolio value $portfolio_value = get_historical_turtle_portfolio_value($date, $portfolioID); ### get current available cash $query = "select shares from turtle_portfolio where symbol = 'CASH' and portfolio_id = " . $portfolioID; $result = queryMysql($query); while ($data = mysql_fetch_row($result)) { $cash = $data[0]; } $risk_value = $portfolio_value * $risk_factor / 100; $current_N = $breakOutStockArray[$x]['ATR']; if ($current_N > 0) { $num_shares = floor($risk_value / ($stop_loss_muptiplier * $current_N)); } /* $purchase_value = $num_shares * $breakOutStockArray[$x][$breakOutSignal]; $stop_loss = $breakOutStockArray[$x][$breakOutSignal] - (2*$current_N); $stop_buy = $breakOutStockArray[$x][$breakOutSignal] + $current_N; */ ## find purchase price ## if target buy price > open (gap down at open, past buy price) ## set purchase price = (open + low ) / 2 ## if open > target buy price > close (regular price action ## set purchase price = target buy price if ($breakOutStockArray[$x]['buy_price'] > $breakOutStockArray[$x]['open']) { $breakOutStockArray[$x]['purchase_price'] = getStockPrice($date, $breakOutStockArray[$x]['symbol'], 'close'); $s = $breakOutStockArray[$x]['symbol']; $p = $breakOutStockArray[$x]['purchase_price']; $b = $breakOutStockArray[$x]['buy_price']; #print "buy price > open: $s buy price = $b purchase price = $p <br />"; } else { $breakOutStockArray[$x]['purchase_price'] = getStockPrice($next_date, $breakOutStockArray[$x]['symbol'], 'close'); $s = $breakOutStockArray[$x]['symbol']; $p = $breakOutStockArray[$x]['purchase_price']; $b = $breakOutStockArray[$x]['buy_price']; $h = $breakOutStockArray[$x]['high']; $l = $breakOutStockArray[$x]['low']; $o = $breakOutStockArray[$x]['open']; $c = $breakOutStockArray[$x]['close']; #print "regular price: $o high $h low $l close $c : $s buy price = $b purchase price = $p <br />"; } ## set purchase price to next day open price ##$breakOutStockArray[$x]['purchase_price'] = getStockPrice($next_date, $breakOutStockArray[$x]['symbol'], 'open'); $h = $breakOutStockArray[$x]['high']; $l = $breakOutStockArray[$x]['low']; $o = $breakOutStockArray[$x]['open']; $c = $breakOutStockArray[$x]['close']; $p = $breakOutStockArray[$x]['purchase_price']; #print "trade date: $date symbol $s close: $c open: $o purchase price = $p <br /> \n"; #$breakOutStockArray[$x]['purchase_price'] = $breakOutStockArray[$x]['buy_price']; $purchase_value = $num_shares * $breakOutStockArray[$x]['purchase_price']; $stop_loss = $breakOutStockArray[$x]['purchase_price'] - $stop_loss_muptiplier * $current_N; $stop_buy = $breakOutStockArray[$x]['purchase_price'] + $current_N; #$current_risk = get_current_risk($portfolioID); $current_risk = get_portfolio_risk($date, $portfolioID); #print "date: $date symbol: ".$breakOutStockArray[$x]['symbol']." current risk :$current_risk \n"; if ($cash > $purchase_value && $current_risk < $max_risk) { $cash = $cash - $purchase_value; $risk_dollar = $num_shares * ($stop_loss_muptiplier * $current_N); $risk_pct = $risk_dollar / $portfolio_value * 100; // insert into turtle_portfolio $my_sql = "insert into turtle_portfolio (portfolio_id, symbol, last_price, shares, cost_basis, stop_loss, stop_buy, risk, risk_pct) "; $my_sql .= "values (" . $portfolioID . ", '" . $breakOutStockArray[$x]['symbol'] . "', "; $my_sql .= $breakOutStockArray[$x]['adj_close'] . ", "; $my_sql .= $num_shares . ", "; // $my_sql .= $breakOutStockArray[$x][$breakOutSignal].", "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $stop_loss . ", "; $my_sql .= $stop_buy . ", "; $my_sql .= $risk_dollar . ", "; $my_sql .= $risk_pct . " )"; #$showOutput = true; if ($showOutput) { print "num: {$x} sql: {$my_sql} <br />"; $p = $breakOutStockArray[$x]['purchase_price']; print "cash: {$cash} purchase price: {$purchase_value} num shares: {$num_shares} purchase value: {$p} current n: {$current_N}<br />"; } $result = queryMysql($my_sql); // trigger on transaction table /* DELIMITER $$ CREATE TRIGGER ins_buy AFTER INSERT ON turtle_portfolio_transaction FOR EACH ROW BEGIN DECLARE xid int; IF (NEW.trade_type = 'BUY') THEN insert IGNORE into open_buy_transaction (portfolio_id, symbol, trade_type, trade_date, shares, price) values (NEW.portfolio_id, NEW.symbol, NEW.trade_type, NEW.trade_date, NEW.shares, NEW.price); ELSE insert IGNORE into transactions (portfolio_id, symbol, sell_date, sell_shares, sell_price) values (NEW.portfolio_id, NEW.symbol, NEW.trade_date, NEW.shares, NEW.price); SET xid = select 1 from transactions; update transactions, open_buy_transaction set transactions.buy_date = open_buy_transaction.trade_date, transactions.buy_shares = open_buy_transaction.shares, transactions.buy_price=open_buy_transaction.price where transactions.symbol = open_buy_transaction and transactions.xid = xid ; delete from open_buy_transaction where symbol = NEW.symbol END IF; END; $$ DELIMITER ; */ // insert into transaction history table $my_sql = "insert into {$tranHistory} (portfolio_id, symbol, trade_type, trade_date, shares, price, risk, risk_pct, vsSpyRank) "; $my_sql .= "values (" . $portfolioID . ", '" . $breakOutStockArray[$x]['symbol'] . "', "; $my_sql .= "'BUY', "; $my_sql .= "'" . $date . "', "; $my_sql .= $num_shares . ", "; // $my_sql .= $breakOutStockArray[$x][$breakOutSignal].", "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $risk_dollar . ", "; $my_sql .= $risk_pct . ", "; $my_sql .= $breakOutStockArray[$x]['vsSpyRank'] . " )"; if ($showOutput) { print "{$my_sql} <br />"; } try { $result = queryMysql($my_sql); } catch (Exception $e) { echo "query: {$my_sql} \n"; echo 'Caught exception: ', $e->getMessage(), "\n"; } // update cash position $my_sql = "update turtle_portfolio set shares = " . $cash . " where symbol = 'CASH' and portfolio_id = " . $portfolioID; if ($showOutput) { print "{$my_sql} <br />"; } $result = queryMysql($my_sql); } else { #print "trade date: $date ran out of money </ br> \n"; break; } $pyramid_mode++; } populateDailyBuyList($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit); }
function crsi_buy_and_sell($date, $breakOutSignal, $ADX_filter, $breakOutOrderBy, $portfolioID, $dailyBuyList, $enterCRSI, $exitCRSI, $enterRange, $enterLimit, $tranHistory, $orderBy, $next_date, $skipFactor, $stop_loss_multiplier, $max_risk, $risk_factor) { global $max_num_holdings; global $max_risk; global $risk_factor; global $stop_loss_multiplier; global $showOutput; global $commission; global $tranHistArray; global $connection; global $portfolio_table; global $transactionHistory; if (!$portfolioID) { $portfolioID = 1; } #$previous_trade_date = getPreviousDate($date); $sell_price = 0; #populateDailyBuyList ($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit); #$breakOutStockArray = getBuyList ($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit, $orderBy); #var_dump ($breakOutStockArray); #$query = "select 'SELL' as buy_sell, a.symbol, shares, risk, risk_pct, b.ATR, b.crsi, d.open*(d.adj_close/d.close) as adj_open "; $query = "select 'SELL' as buy_sell, a.symbol, shares, risk, risk_pct, b.ATR, b.crsi "; #$query .= "from $portfolio_table a, quotes_memory b , quotes_memory d "; $query .= "from {$portfolio_table} a, quotes_memory b "; $query .= "where a.symbol = b.symbol "; $query .= "and a.portfolio_id = " . $portfolioID . " "; $query .= "and a.symbol != 'CASH' "; $query .= "and b.crsi > {$exitCRSI} "; $query .= "and b.trade_date = '" . $date . "' "; #$query .= "and b.symbol = d.symbol and b.trade_date_id = d.trade_date_id - 1 "; $query .= " UNION "; #$query .= "select 'BUY' as buy_sell, a.symbol, 0, 0, 0, a.ATR, a.crsi, d.open*(d.adj_close/d.close) as adj_open "; $query .= "select 'BUY' as buy_sell, a.symbol, 0, 0, 0, a.ATR, a.crsi "; #$query .= "from quotes_memory a, $dailyBuyList c , quotes_memory d "; $query .= "from quotes_memory a, {$dailyBuyList} c "; $query .= " where a.trade_date = '" . $date . "'"; $query .= " and c.portfolio_id = " . $portfolioID; $query .= " and a.symbol = c.symbol "; $query .= " and a.low * (a.adj_close / a.close) < c.buy_price"; $query .= " and a.symbol not in (select symbol from {$portfolio_table} where portfolio_id = " . $portfolioID . ") "; $query .= " and a.ATR > 0 "; #$query .= " and a.symbol = d.symbol and a.trade_date_id = d.trade_date_id - 1"; $query .= " order by {$orderBy}"; #echo "$query ", PHP_EOL; $result = queryMysql($query); $ph = array(); $buy_list = array(); $sell_list = array(); $buy_count = 0; $sell_count = 0; $i = 0; while ($data = mysql_fetch_row($result)) { $ph[$i]['buy_sell'] = str_replace("\"", "", $data[0]); $ph[$i]['symbol'] = str_replace("\"", "", $data[1]); $ph[$i]['shares'] = str_replace("\"", "", $data[2]); $ph[$i]['risk'] = str_replace("\"", "", $data[3]); $ph[$i]['risk_pct'] = str_replace("\"", "", $data[4]); $ph[$i]['ATR'] = str_replace("\"", "", $data[5]); $ph[$i]['crsi'] = str_replace("\"", "", $data[6]); $i++; if ($data[0] == "SELL") { $sell_list[$sell_count]['symbol'] = str_replace("\"", "", $data[1]); $sell_list[$sell_count]['shares'] = str_replace("\"", "", $data[2]); $sell_list[$sell_count]['risk'] = str_replace("\"", "", $data[3]); $sell_list[$sell_count]['risk_pct'] = str_replace("\"", "", $data[4]); $sell_list[$sell_count]['ATR'] = str_replace("\"", "", $data[5]); $sell_list[$sell_count]['crsi'] = str_replace("\"", "", $data[6]); $sell_count++; } else { $buy_list[$buy_count]['symbol'] = str_replace("\"", "", $data[1]); $buy_list[$buy_count]['shares'] = str_replace("\"", "", $data[2]); $buy_list[$buy_count]['risk'] = str_replace("\"", "", $data[3]); $buy_list[$buy_count]['risk_pct'] = str_replace("\"", "", $data[4]); $buy_list[$buy_count]['ATR'] = str_replace("\"", "", $data[5]); $buy_list[$buy_count]['crsi'] = str_replace("\"", "", $data[6]); $buy_count++; } } $total_sale = 0; if ($sell_count > 0) { $delete_query = "delete from {$portfolio_table} where portfolio_id = " . $portfolioID . " and symbol in (NULL "; for ($x = 0; $x < $sell_count; $x++) { $sell_price = getStockPrice($next_date, $sell_list[$x]['symbol'], 'open'); $stock_sales = $sell_list[$x]['shares'] * $sell_price - $commission; $total_sale += $stock_sales; $delete_query .= ",'" . $sell_list[$x]['symbol'] . "'"; $insert_transaction_history = "insert into {$tranHistory} values (" . $portfolioID . ", '" . $sell_list[$x]['symbol'] . "', 'SELL', '" . $date . "', " . $sell_list[$x]['shares'] . ", " . $sell_price . ", " . $sell_list[$x]['risk'] . ", " . $sell_list[$x]['risk_pct'] . ", null, null, null, 0)"; $tmpTransaction = array(); $tmpTransaction['portfolioID'] = $portfolioID; $tmpTransaction['symbol'] = $sell_list[$x]['symbol']; $tmpTransaction['buy_sell'] = "SELL"; $tmpTransaction['trade_date'] = $date; $tmpTransaction['shares'] = $sell_list[$x]['shares']; $tmpTransaction['price'] = $sell_price; $tmpTransaction['risk'] = $sell_list[$x]['risk']; $tmpTransaction['risk_pct'] = $sell_list[$x]['risk_pct']; $tmpTransaction['trade_time'] = "null"; $tmpTransaction['gain_loss'] = 0; $tmpTransaction['holding_period'] = 0; $tmpTransaction['vsSpyRank'] = 0; array_push($transactionHistory, $tmpTransaction); array_push($tranHistArray, $insert_transaction_history); } $delete_query .= ")"; $result = queryMysql($delete_query); $update_portfolio_query = "update {$portfolio_table} set shares = shares + " . $total_sale . " where portfolio_id = " . $portfolioID . " and symbol ='CASH'"; $result = queryMysql($update_portfolio_query); } ###crsi buy #$breakOutStockArray = getBuyList ($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit, $orderBy); $breakOutStockArray = $buy_list; $sizeBuyList = sizeof($breakOutStockArray); if (!$skipFactor) { $skipFactor = 0.05; } $len_array = count($breakOutStockArray); $portfolio_value = 0; $current_pos = 0; $next_buy_point = 100000; $stop_loss = 0; $num_shares = 0; $current_N = 0; $risk_value = 0; $purchase_value = 0; $sim_start_day = 55; $pyramid_mode = 0; $stop_loss = 0; $current_trade_date_id = 0; $workingArray = $breakOutStockArray; $adxArray = ""; $adxCount = 1; $len_array = count($breakOutStockArray); $portfolio_value = get_historical_turtle_portfolio_value($date, $portfolioID); $query = "select shares from {$portfolio_table} where symbol = 'CASH' and portfolio_id = " . $portfolioID; $result = queryMysql($query); while ($data = mysql_fetch_row($result)) { $cash = $data[0]; } $current_risk = get_portfolio_risk($date, $portfolioID); $buy_array = array(); $skipNum = ceil($skipFactor * $sizeBuyList); #for ($x=1; $x < $len_array; $x++) { for ($x = $skipNum; $x < $sizeBuyList; $x++) { ### get portfolio value #$portfolio_value = get_historical_turtle_portfolio_value($date, $portfolioID); ### get current available cash #$query = "select shares from turtle_portfolio where symbol = 'CASH' and portfolio_id = ".$portfolioID; #$result = queryMysql($query); #while ($data = mysql_fetch_row($result)) { # $cash = $data[0]; #} $risk_value = $portfolio_value * $risk_factor / 100; $current_N = $breakOutStockArray[$x]['ATR']; if ($current_N > 0) { $num_shares = floor($risk_value / ($stop_loss_multiplier * $current_N)); } ## set purchase price to next day open price $breakOutStockArray[$x]['purchase_price'] = getStockPrice($next_date, $breakOutStockArray[$x]['symbol'], 'open'); if (!$breakOutStockArray[$x]['purchase_price']) { break; } $purchase_value = $num_shares * $breakOutStockArray[$x]['purchase_price'] + $commission; $stop_loss = $breakOutStockArray[$x]['purchase_price'] - $stop_loss_multiplier * $current_N; $stop_buy = $breakOutStockArray[$x]['purchase_price'] + $current_N; #echo "symbol: ", $breakOutStockArray[$x]['symbol'], " cash: $cash purchase: $purchase_value current risk: $current_risk max risk: $max_risk ", PHP_EOL; if ($cash > $purchase_value && $current_risk < $max_risk) { $cash = $cash - $purchase_value; $risk_dollar = $num_shares * ($stop_loss_multiplier * $current_N); $risk_pct = $risk_dollar / $portfolio_value * 100; // insert into turtle_portfolio $my_sql = "insert into {$portfolio_table} (portfolio_id, symbol, last_price, shares, cost_basis, stop_loss, stop_buy, risk, risk_pct) "; $my_sql .= "values (" . $portfolioID . ", '" . $breakOutStockArray[$x]['symbol'] . "', "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $num_shares . ", "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $stop_loss . ", "; $my_sql .= $stop_buy . ", "; $my_sql .= $risk_dollar . ", "; $my_sql .= $risk_pct . " )"; array_push($buy_array, $my_sql); $current_risk += $risk_pct; #print "current risk after adding risk dollar: current risk: $current_risk risk pct added: $risk_pct max risk: $max_risk \n"; #$showOutput = true; if ($showOutput) { print "num: {$x} sql: {$my_sql} <br />"; $p = $breakOutStockArray[$x]['purchase_price']; print "cash: {$cash} purchase price: {$purchase_value} num shares: {$num_shares} purchase value: {$p} current n: {$current_N}<br />"; } // insert into transaction history table $my_sql = "insert into {$tranHistory} (portfolio_id, symbol, trade_type, trade_date, shares, price, risk, risk_pct, vsSpyRank) "; $my_sql .= "values (" . $portfolioID . ", '" . $breakOutStockArray[$x]['symbol'] . "', "; $my_sql .= "'BUY', "; $my_sql .= "'" . $date . "', "; $my_sql .= $num_shares . ", "; $my_sql .= $breakOutStockArray[$x]['purchase_price'] . ", "; $my_sql .= $risk_dollar . ", "; $my_sql .= $risk_pct . ", "; $my_sql .= "0 )"; array_push($tranHistArray, $my_sql); $tmpTransaction = array(); $tmpTransaction['portfolioID'] = $portfolioID; $tmpTransaction['symbol'] = $breakOutStockArray[$x]['symbol']; $tmpTransaction['buy_sell'] = "BUY"; $tmpTransaction['trade_date'] = $date; $tmpTransaction['shares'] = $num_shares; $tmpTransaction['price'] = $breakOutStockArray[$x]['purchase_price']; $tmpTransaction['risk'] = $risk_dollar; $tmpTransaction['risk_pct'] = $risk_pct; $tmpTransaction['trade_time'] = "null"; $tmpTransaction['gain_loss'] = 0; $tmpTransaction['holding_period'] = 0; $tmpTransaction['vsSpyRank'] = 0; array_push($transactionHistory, $tmpTransaction); if ($showOutput) { print "{$my_sql} <br />"; } #try { # $result = queryMysql($my_sql); #} catch (Exception $e) { # echo "query: $my_sql \n"; # echo 'Caught exception: ', $e->getMessage(), "\n"; #} // update cash position #$my_sql = "update turtle_portfolio set shares = ".$cash." where symbol = 'CASH' and portfolio_id = ".$portfolioID; #$result = queryMysql($my_sql); } else { #print "trade date: $date ran out of money </ br> \n"; break; } $pyramid_mode++; } $my_sql = "update {$portfolio_table} set shares = " . $cash . " where symbol = 'CASH' and portfolio_id = " . $portfolioID; $result = queryMysql($my_sql); foreach ($buy_array as $buy) { try { queryMysql($buy); } catch (Exception $e) { echo "Query: {$buy} \n"; echo 'Caught exception: ', $e->getMessage(), "\n"; } } populateDailyBuyList($date, $enterCRSI, $enterRange, $portfolioID, $dailyBuyList, $enterLimit); }