Esempio n. 1
0
 public function actionTest()
 {
     $start = time();
     Yii::app()->cache->flush();
     Yii::app()->db->createCommand()->truncateTable(Buy::model()->tableName());
     Yii::app()->db->createCommand()->truncateTable(Sell::model()->tableName());
     Yii::app()->db->createCommand()->truncateTable(Order::model()->tableName());
     Yii::app()->db->createCommand()->truncateTable(Balance::model()->tableName());
     // Тест на 10 000 руб.
     Status::setParam('balance', 10000);
     Status::setParam('balance_btc', 0);
     $exs = Exchange::getAllByDt('btc_rur', '2013-12-16', '2014-01-06');
     $cnt = 0;
     foreach ($exs as $exchange) {
         $obj = new stdClass();
         $obj->dtm = $exchange['dt'];
         $obj->buy = $exchange['buy'];
         $obj->sell = $exchange['sell'];
         $cnt++;
         $bot = new Bot($obj);
         $bot->run();
     }
     $end = time();
     echo '<b>Elapsed time: ' . ($end - $start) / 60 . ' min.<br/>';
     echo '<b>Steps count: ' . $cnt . '<br/>';
 }
Esempio n. 2
0
 /**
  * Show the form for creating a new resource.
  *
  * @return Response
  */
 public function create()
 {
     $input = Input::all();
     $dateX = \Carbon\Carbon::now();
     $p_status = $input['payment_status'];
     $data = ['price' => $input['frm_payable'], 'payment_status' => $input['payment_status'], 'paid' => $input['frm_ammount'], 'due' => $input['frm_due'], 'installments' => $input['frm_inst_no'], 'cus_id' => $input['cus_id'], 'inv_id' => $input['inv_id'], 'sold_date' => $dateX->year . "-" . $dateX->month . "-" . $dateX->day, 'vat' => $input['frm_payVat'], 'bank_int' => $input['frm_payInt'], 'total_billed' => $input['total_bill'], 'ref_id' => $input['ref_id']];
     if ($p_status == 'cash') {
         if ($data['due'] != 0) {
             return ['data' => 0, 'massage' => 'Please paid full amount or choose installment', 'status' => 0];
         } else {
             $sold = Sell::create($data);
             $payment = ['car_sold_id' => $sold->id, 'cus_id' => $sold->cus_id, 'paid' => $sold->paid, 'interest' => 0, 'due_date' => $sold->sold_date, 'comment' => 'sold with cash', 'transection_id' => 1];
             $update = DB::table('inventory')->where('id', '=', $sold->inv_id)->update(['is_sell' => '1']);
             $paid = CusPay::create($payment);
             return ['data' => ['sold_info' => ['id' => $sold->id, 'moto_price' => $sold->price, 'vat' => $sold->vat, 'bank_int' => $sold->bank_int, 'sold_date' => $sold->sold_date, 'total_billed' => $sold->total_billed, 'installments' => $sold->installments, 'paid' => $sold->paid, 'due' => $sold->due], 'paid_id' => $paid->id], 'massage' => 'Success to payment', 'status' => 1];
         }
     } else {
         $sold = Sell::create($data);
         $dateLast = \Carbon\Carbon::parse($sold->sold_date)->addMonths($data['installments']);
         $dateNext = \Carbon\Carbon::parse($sold->sold_date)->addMonth();
         $payment = ['car_sold_id' => $sold->id, 'cus_id' => $sold->cus_id, 'paid' => $sold->paid, 'interest' => 0, 'due_date' => $sold->sold_date, 'transection_id' => 1, 'comment' => 'sold with due'];
         $loan = ['sold_id' => $sold->id, 'rate' => $input['frm_inst_rate'], 'total_inst' => $sold->installments, 'current_inst' => 1, 'current_paid' => $sold->paid, 'current_due' => $sold->due, 'next_pay_date' => $dateNext->year . "-" . $dateNext->month . "-" . $dateNext->day, 'end_date' => $dateLast->year . "-" . $dateLast->month . "-" . $dateLast->day];
         $setLoan = Loan::create($loan);
         $update = DB::table('inventory')->where('id', '=', $sold->inv_id)->update(['is_sell' => '1']);
         $paid = CusPay::create($payment);
         return ['data' => ['sold_info' => ['id' => $sold->id, 'moto_price' => $sold->price, 'vat' => $sold->vat, 'bank_int' => $sold->bank_int, 'sold_date' => $sold->sold_date, 'total_billed' => $sold->total_billed, 'paid' => $sold->paid, 'due' => $sold->due, 'total_inst' => $setLoan->total_inst, 'rate' => $setLoan->rate], 'paid_id' => $paid->id, 'loan_id' => $setLoan->id], 'massage' => 'Success to payment', 'status' => 1];
     }
 }
Esempio n. 3
0
function sell_edit()
{
    $session = Session::getInstance();
    if (!$session->checkLogin()) {
        return false;
    }
    $sell = new Sell();
    $sell->id = isset($_POST['sell']) ? $_POST['sell'] : "";
    $sell->status = isset($_POST['status']) ? $_POST['status'] : "";
    $sell->update();
    if (isset($_POST['payment']) && is_numeric($_POST['payment'])) {
        $sellPayment = new SellPayment();
        $sellPayment->sellid = isset($_POST['sell']) ? $_POST['sell'] : "";
        $sellPayment->amount = isset($_POST['payment']) ? $_POST['payment'] : "";
        $sellPayment->add();
    }
}
Esempio n. 4
0
 public function __construct()
 {
     //Инициализируем переменные
     $this->fee = 0.2 / 100;
     // Комиссия за операцию
     $this->imp_div = 1 / 100;
     // Процент при котором считать подъем/падение = 1%
     //$this->buy_sum = 350; // Покупать на 300 руб.
     $this->buy_value = 0.01;
     // Сколько покупать
     $this->buystep_n = 5;
     // Смотрим по ... блоков
     $this->sellstep_n = 4;
     // Смотрим по ... блоков
     $this->analize_period = 60 * 60 * 1;
     // Период за который анализируем график (6 часов)
     $this->min_income = 10;
     // Мин. доход
     $this->balance = Status::getParam('balance');
     $this->balance_btc = Status::getParam('balance_btc');
     $this->order_cnt = 0;
     $this->bought = Buy::model()->with('sell')->findAll();
     $this->total_income = Sell::getTotalIncome();
 }
Esempio n. 5
0
 public function actionChart($type = 'btc_rur')
 {
     $buy = new Buy();
     $exch = Exchange::getAllByDt('btc_rur', '2013-12-16', '2014-01-06');
     $data_buy = array();
     $data_sell = array();
     foreach ($exch as $item) {
         $tm = strtotime($item['dt']) * 1000 + 4 * 60 * 60 * 1000;
         $data_buy[] = array($tm, (double) $item['buy']);
         $data_sell[] = array($tm, (double) $item['sell']);
     }
     // Покупки
     $orders = Order::model()->findAll();
     $lastEx = Exchange::getLast();
     $status['total_income'] = Sell::getTotalIncome();
     $status['balance'] = Status::getParam('balance');
     $status['balance_btc'] = Status::getParam('balance_btc');
     $status['total_balance'] = $status['balance'] + $status['balance_btc'] * $lastEx->sell;
     $this->render('chart', array('data_buy' => json_encode($data_buy), 'data_sell' => json_encode($data_sell), 'orders' => $orders, 'status' => $status));
 }
<p class="form-title">Venta</p>
<?php 
if (!Forms::checkPermission(FORM_SELL_DETAIL)) {
    return;
}
require 'inc/class.sell.php';
require 'inc/class.formatter.php';
$sellid = isset($_GET['sell']) && is_numeric($_GET['sell']) ? $_GET['sell'] : false;
$log = Log::getInstance();
$isValid = true;
if (!$sellid) {
    $log->addError("No existen datos de Venta solicitada.");
    $isValid = false;
}
$sell = new Sell();
if (!$sell->read($sellid, true)) {
    $log->addError("No existen datos de Venta solicitada.");
    $isValid = false;
}
$details = SellDetail::getAll($sellid);
$payments = SellPayment::getAll($sellid);
include 'inc/widget/error.php';
if ($isValid) {
    ?>
<table class="form">
<tr>
	<td class="label">Venta Nro.:</td>
	<td><?php 
    echo $sell->id;
    ?>
</td>
<p class="form-title">Venta</p>
<?php 
if (!Forms::checkPermission(FORM_SELL_EDIT)) {
    return;
}
require 'inc/class.sell.php';
require 'inc/class.formatter.php';
$sellid = isset($_GET['sell']) && is_numeric($_GET['sell']) ? $_GET['sell'] : false;
$log = Log::getInstance();
$isValid = true;
if (!$sellid) {
    $log->addError("No existen datos de Venta solicitada.");
    $isValid = false;
}
$sell = new Sell();
if (!$sell->read($sellid)) {
    $log->addError("No existen datos de Venta solicitada.");
    $isValid = false;
}
$details = SellDetail::getAll($sellid);
$payments = SellPayment::getAll($sellid);
include 'inc/widget/error.php';
if (isset($_POST['page']) && isset($_POST['sell']) && !$log->isError()) {
    include 'inc/widget/success.php';
}
if ($isValid) {
    ?>
<form action="" method="POST" name="form1">
	<table class="form">
	<tr>
		<td class="label">Venta Nro.:</td>
Esempio n. 8
0
<?php

$bikri = "selected";
include 'template/blankStart.php';
?>
<link rel="stylesheet" href="../view/template/css/table-panel.css">
<?php 
include_once '../view/sections/sell-nav.php';
include 'sections/modals/sell-modals.php';
include_once dirname(__FILE__) . "/../model/client.php";
if ($_POST) {
    include_once dirname(__FILE__) . "/../model/sell.php";
    $sell = new Sell($_POST["clientName"]);
    $sell->makeSell();
    echo "<span id=\"success\"></span>";
    //initiate memo making process
    //get a new memo number
    //using the client name get his past due
    //then calulate the new due step by step
    // {
    // 	each of the products should be saved in the log
    // 	the raw total is calculated
    // }
}
?>
 <!--=================================
 modals
 =================================-->
 <div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
</th>
		<th style="width:8em">Saldo <?php 
echo SB_CURRENCY;
?>
</th>
		<th colspan="2">&nbsp;</th>
	</tr>
</thead>
<tbody>
	<?php 
foreach ($selles as $sell) {
    echo "<tr>";
    echo "<td class='number'>{$sell->id}</td>";
    echo "<td class='date'>" . Formatter::date($sell->date) . "</td>";
    echo "<td>{$sell->provider}</td>";
    echo "<td>{$PURCHASE_STATUS[$sell->status]}</td>";
    echo "<td class='number'>" . Formatter::number($sell->amount) . "</td>";
    echo "<td class='number'>" . Formatter::number($sell->amount - Sell::getAmountPaid($sell->id)) . "</td>";
    echo "<td class='ui-state-default'><a href='index.php?pages=sell_detail&sell={$sell->id}' title='Ver'>" . ICON_ZOOMIN . "</a></td>";
    echo "<td class='ui-state-default'><a href='index.php?pages=sell_edit&sell={$sell->id}' title='Editar'>" . ICON_PENCIL . "</a></td>";
    echo "</tr>";
}
?>
</tbody>
</table>

<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery('.default tbody tr:odd').addClass('alternate');
});
</script>
Esempio n. 10
0
 public function NeedSell()
 {
     // Составляем причину покупки
     $reason = array();
     $curtime = $this->curtime;
     //Дата операции
     $dt = date('Y-m-d H:i:s', $curtime);
     //Смотрим, что продать
     //$bought = Buy::model()->findAll(array('condition'=>'sold=0 and order_id=0'));
     $bought = Buy::getNotSold();
     // Если нечего продавать
     if (sizeof($bought) == 0) {
         return false;
     }
     /*
     // Если текущая цена ниже средней не продаем
     $from = date('Y-m-d H:i:s',$this->curtime-60*60*24*7);
     $avg_sell = Exchange::getAvg('sell', $from,  date('Y-m-d H:i:s', $this->curtime));
     if ($avg_sell>$this->current_exchange->sell)
     {
     	Log::notsell('Цена ниже средней за 7 дн. ('.$avg_sell.'>'.$this->current_exchange->buy.'), не продаем.');
     	return false;
     }
     else
     	$reason['avg_price'] = 'Текущая цена выше средней за 7 дней '.('.$this->avg_sell.'>'.$this->current_exchange->buy.'); 
     */
     // Проверяем была ли уже продажа за последнее время, если была и цена была более выгодная чем текущая то не продаем
     $lastSell = Sell::getLast();
     if ($lastSell) {
         $tm = strtotime($lastSell->dtm) + self::min_sell_interval;
         $diff = 1 - $lastSell->price / $this->current_exchange->sell;
         if ($tm > $this->curtime && $diff < $this->sell_imp_dif) {
             Log::notsell('Уже была продажа, ждем до ' . date('Y-m-d H:i:s', $tm) . ' текущая цена ' . $this->current_exchange->sell . ' меньше прошлой ' . $lastSell->price);
             return false;
         } else {
             $reason['avg_price'] = 'Прошлая продажа была ' . ($this->curtime - strtotime($lastSell->dtm)) / 60 . ' мин. назад (допустимы покупки раз в ' . self::min_sell_interval / 60 . ' мин. при отсутствии ощутимого роста цены), цена отличалась от текущей на ' . $diff * 100 . '%, минимальное отличие должно быть ' . $this->sell_imp_dif * 100 . '% ';
         }
     }
     //Перебираем периоды
     $all_tracks = array();
     foreach ($this->sell_periods as $period) {
         $all_tracks[] = $this->getGraphImage($curtime, $period, 'sell', $this->sell_imp_dif);
     }
     //Анализируем треки
     $tracks = $this->getSellTracks($all_tracks);
     if (sizeof($tracks) == 0) {
         Log::notsell('Нет подходящих треков для продажи');
         return false;
     }
     $reason['tracks'] = $tracks;
     $reason['all_tracks'] = $all_tracks;
     // Совершаем вынужденные продажи
     $this->NecesarySell($all_tracks, $bought);
     // Ищем выгодные продажи
     foreach ($bought as $key => $buy) {
         // Цена продажи
         $curcost = $buy->count * $this->current_exchange->sell * (1 - self::fee);
         // Сколько заработаем при продаже (комиссия была уже вычтена в btc при покупке)
         $income = $curcost - $buy->summ;
         // Достаточно ли заработаем
         if ($income / $buy->summ < self::min_income) {
             if ($income > 0) {
                 Log::notsell('Не продали (№' . $buy->id . '), доход слишком мал ' . $income . ' < ' . self::min_income * $curcost . ' купил за ' . $buy->summ . ' можно продать за ' . $curcost . ' sell=' . $this->current_exchange->sell);
             }
             continue;
         }
         // Записываем причину покупки
         $reason['buy'] = 'Найдена подходящая продажа №' . $buy->id . ' с доходом от сделки ' . $income . ' руб., что составляет ' . $income / $buy->summ * 100 . '% от цены покупки';
         Log::Add('Начало продажи №' . $buy->id);
         $this->startSell($buy, $reason);
         //unset($bought[$key]);
         break;
         // не более одной продажи по расчету за раз
     }
 }
<p class="form-title">Ventas por Cobrar</p>
<?php 
if (!Forms::checkPermission(FORM_SELL_OUTSTANDING)) {
    return;
}
require 'inc/class.sell.php';
require 'inc/class.formatter.php';
$selles = Sell::getAllOutstanding("`date`", "DESC");
?>

<table class="default">
<thead>
	<tr>
		<th style="width:8em">Venta Nro.</th>
		<th style="width:8em">Fecha</th>
		<th style="width:12em">Cliente</th>
		<th>Estado</th>
		<th style="width:8em">Monto <?php 
echo SB_CURRENCY;
?>
</th>
		<th style="width:8em">Saldo <?php 
echo SB_CURRENCY;
?>
</th>
		<th colspan="2">&nbsp;</th>
	</tr>
</thead>
<tbody>
	<?php 
foreach ($selles as $sell) {
Esempio n. 12
0
 public static function make($order)
 {
     $buy = $order->buy;
     $buy->sold += $order->count;
     $buy->update(array('sold'));
     // Расчитываем сумму покупки, так как нужно считать для продажи доли
     $buy_summ = $buy->summ / $buy->count * $order->count;
     $sell = new Sell();
     $sell->buy_id = $buy->id;
     $sell->price = $order->price;
     $sell->count = $order->count;
     $sell->summ = $order->summ - $order->fee;
     $sell->fee = $order->fee;
     $sell->income = $order->summ - $buy_summ - $sell->fee;
     $sell->dtm = $order->close_dtm;
     $sell->save();
     return $sell;
 }