<?php
//entrada dos parametro via GET (moedid/perid)
$moedid = filter_input(INPUT_GET, 'moedid', FILTER_DEFAULT);
$perid = filter_input(INPUT_GET, 'perid', FILTER_VALIDATE_INT);

//montando as datas de acordo com o periodo
$data_ini = date("Y-m-d");
$data_fim = date('Y-m-d', strtotime("-{$perid} month", strtotime($data_ini)));
?>
<ul class="page-breadcrumb breadcrumb">
    <li>
        <span>Indice</span>
    </li>
</ul>
<br>
<div class="row">
    <div class="col-md-12">
        <form method="POST" action="javascript:filtro();" class="form-inline margin-bottom-40" role="form">
            <div class="form-group form-md-line-input">
                <select class="form-control" name="moedid" id="campo_moeda">
                    <option value="">Selecione a moeda</option>
                    <?php
                    $Read = new Read;
                    $Read->ExeRead("tp_moedas");
                    if ($Read->getResult()):
                        foreach ($Read->getResult() as $moedas):
                            extract($moedas);
                            $sel = '';
                            if (isset($moedid) && $moedid == $moeda_codigo) {
                                $sel = 'selected';
                            }
                            ?>

                            <option <?= $sel; ?> value="<?= $moeda_codigo; ?>"><?= $moeda_nome; ?></option>

                            <?php
                        endforeach;
                    endif;
                    ?>
                </select>
                <div class="form-control-focus"> </div>
            </div>
            <div class="form-group form-md-line-input has-success">
                <select class="form-control" name="perid" id="campo_periodo">
                    <option value="">Selecione o periodo</option>
                    <?php
                    $Read = new Read;
                    $Read->ExeRead("tp_periodos", "ORDER BY periodo_meses ASC");
                    if ($Read->getResult()):
                        foreach ($Read->getResult() as $periodos):
                            extract($periodos);
                            $sel = '';
                            if (isset($perid) && $perid == $periodo_meses) {
                                $sel = 'selected';
                            }
                            ?>

                            <option <?= $sel; ?> value="<?= $periodo_meses; ?>"><?= $periodo_nome; ?></option>

                            <?php
                        endforeach;
                    endif;
                    ?>
                </select>
                <div class="form-control-focus"> </div>
            </div>
            <button type="button" onclick="filtro()" class="btn btn-sm btn-success table-group-action-submit"> <i class="fa fa-check"></i> Carregar</button>

        </form>
    </div>
</div>

<?php
if ($moedid == '' || $perid == ''):
    WSErro("Selecione a moeda e o periodo para consulta!", WS_INFOR);
else:
    ?>
    <!-- titulos aberto -->
    <div class="row">
        <div class="col-md-7">
            <div class="table-scrollable">
                <table class="table table-bordered table-hover">
                    <?php
                    $Read = new Read;
                    $Read->ExeRead("tp_indice", "WHERE CFTC_Contract_Market_Code = :moeda LIMIT 1", "moeda={$moedid}");

                    foreach ($Read->getResult() as $indices):
                        extract($indices);
                        $total = $NonComm_Positions_Long_All + $NonComm_Postions_Spread_All + $Comm_Positions_Long_All + $NonRept_Positions_Long_All;
                    endforeach;
                    ?>
                    <thead>
                        <tr>
                            <th class="warning" colspan="5"> Contratos em Aberto </th>
                            <th class="active"> Total </th>
                            <th class="active"> <?= $total; ?> </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="success"> NC Long </td>
                            <td class="success"> NC Short </td>
                            <td class="success"> Spread </td>
                            <td class="success"> CC Long </td>
                            <td class="success"> CC Short </td>
                            <td class="success"> VV Long </td>
                            <td class="success"> VV Short </td>
                        </tr>
                        <tr>
                            <td class="active"> <?= $NonComm_Positions_Long_All; ?> </td>
                            <td class="active"> <?= $NonComm_Positions_Short_All; ?> </td>
                            <td class="active"> <?= $NonComm_Postions_Spread_All; ?> </td>
                            <td class="active"> <?= $Comm_Positions_Long_All; ?> </td>
                            <td class="active"> <?= $Comm_Positions_Short_All; ?> </td>
                            <td class="active"> <?= $NonRept_Positions_Long_All; ?> </td>
                            <td class="active"> <?= $NonRept_Positions_Short_All; ?> </td>
                        </tr>
                        <tr>
                            <td> <?= number_format(($NonComm_Positions_Long_All * 100) / $total, 2, ',', '.'); ?>% </td>
                            <td class="active"> <?= number_format(($NonComm_Positions_Short_All * 100) / $total, 2, ',', '.'); ?>% </td>
                            <td class="active"> <?= number_format(($NonComm_Postions_Spread_All * 100) / $total, 2, ',', '.'); ?>% </td>
                            <td class="active"> <?= number_format(($Comm_Positions_Long_All * 100) / $total, 2, ',', '.'); ?>% </td>
                            <td class="active"> <?= number_format(($Comm_Positions_Short_All * 100) / $total, 2, ',', '.'); ?>% </td>
                            <td class="active"> <?= number_format(($NonRept_Positions_Long_All * 100) / $total, 2, ',', '.'); ?>% </td>
                            <td class="active"> <?= number_format(($NonRept_Positions_Short_All * 100) / $total, 2, ',', '.'); ?>% </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="col-md-5">
            <div class="table-scrollable">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th class="success" style="text-align:center"> Preço </th>
                            <th class="success" style="text-align:center"> Volume </th>
                            <th class="success" style="text-align:center"> OI </th>
                            <th class="success" style="text-align:center"> Trader </th>
                            <th class="success"> Situação  </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active"> FORTE </td>
                        </tr>
                        <tr>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active" class="bg-yellow-crusta" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active"> FORTE </td>
                        </tr>
                        <tr>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-up font-green-jungle"></i> </td>
                            <td class="active"> FRACA </td>
                        </tr>
                        <tr>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active" style="text-align:center"> <i class="fa fa-arrow-down font-red-thunderbird"></i> </td>
                            <td class="active"> FRACA </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- END titulos aberto -->

    <?php
    ///////////// calcular média da tabela///////
    ////
    $i = 0;
    $Read->ExeRead("tp_indice", "WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC LIMIT 12", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    foreach ($Read->getResult() as $rs):
        $arrNonCommLong[$i] = $rs['NonComm_Positions_Long_All'];
        $arrNonCommShort[$i] = $rs['NonComm_Positions_Short_All'];
        $arrTotalNonComm[$i] = $rs['NonComm_Positions_Long_All'] + $rs['NonComm_Positions_Short_All'];
        $arrNetNonComm[$i] = $rs['NonComm_Positions_Long_All'] - $rs['NonComm_Positions_Short_All'];

        $arrcCommLong[$i] = $rs['Comm_Positions_Long_All'];
        $arrcCommShort[$i] = $rs['Comm_Positions_Short_All'];
        $arrTotalcComm[$i] = $rs['Comm_Positions_Long_All'] + $rs['Comm_Positions_Short_All'];
        $arrNetcComm[$i] = $rs['Comm_Positions_Long_All'] - $rs['Comm_Positions_Short_All'];
        $arrDifNet[$i] = $arrNetNonComm[$i] - $arrNetcComm[$i];
        $i++;
    endforeach;

    // calculando as médias do não comercial
    $nonLong = round(array_sum($arrNonCommLong) / count($arrNonCommLong));
    $nonShort = round(array_sum($arrNonCommShort) / count($arrNonCommShort));
    $nonTotal = round(array_sum($arrTotalNonComm) / count($arrTotalNonComm));
    $nonNet = round(array_sum($arrNetNonComm) / count($arrNetNonComm));
    // calculando as médias do comercial
    $cLong = round(array_sum($arrcCommLong) / count($arrcCommLong));
    $cShort = round(array_sum($arrcCommShort) / count($arrcCommShort));
    $cTotal = round(array_sum($arrTotalcComm) / count($arrTotalcComm));
    $cNet = round(array_sum($arrNetcComm) / count($arrNetcComm));
    $cDif = round(array_sum($arrDifNet) / count($arrDifNet));

    ////
    //////////// Fim do calculo da média ///////
    ?>
    <!-- tabela indice -->
    <div class="row">
        <div class="col-md-12">
            <div class="table-scrollable">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <!-- função para ascrecentar meses a data -->
                            <?php $dataN = date('Y-m-d', strtotime("+4 month", strtotime("2018/09/15"))); ?>
                            <th class="warning"></th>
                            <th class="warning"> <?= $nonLong; ?> </th>
                            <th class="warning"> <?= $nonShort; ?> </th>
                            <th class="warning"> <?= $nonTotal; ?> </th>
                            <th class="warning" colspan="2"> Não Comercial </th>
                            <th class="warning"> <?= $nonNet; ?> </th>
                            <th class="warning" rowspan="2"> Long </th>
                            <th class="warning" rowspan="2"> Short </th>
                            <th rowspan="2">  </th>
                            <th class="warning"> <?= $cLong; ?> </th>
                            <th class="warning"> <?= $cShort; ?> </th>
                            <th class="warning"> <?= $cTotal; ?> </th>
                            <th class="warning" colspan="2"> Comercial </th>
                            <th class="warning"> <?= $cNet; ?> </th>
                            <th class="warning"> <?= $cDif; ?> </th>
                        </tr>
                        <tr>
                            <th class="success"> Data </th>
                            <th class="success"> Long </th>
                            <th class="success"> Short </th>
                            <th class="success"> Total </th>
                            <th class="success"> % Long </th>
                            <th class="success"> % Short </th>
                            <th class="success"> Net Pos. </th>

                            <th class="success"> Long </th>
                            <th class="success"> Short </th>
                            <th class="success"> Total </th>
                            <th class="success"> % Long </th>
                            <th class="success"> % Short </th>
                            <th class="success"> Net Pos. </th>
                            <th class="success"> Dif Net </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $Read->ExeRead("tp_indice", "WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC LIMIT 20", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
                        foreach ($Read->getResult() as $rs):
                            extract($rs);

                            //montando valores
                            $TotalNonComm = $NonComm_Positions_Long_All + $NonComm_Positions_Short_All;
                            $PorcNonCommLong = number_format(($NonComm_Positions_Long_All * 100) / $TotalNonComm);
                            $PorcNonCommShort = number_format(($NonComm_Positions_Short_All * 100) / $TotalNonComm);
                            $NetNonComm = $NonComm_Positions_Long_All - $NonComm_Positions_Short_All;
                            $DivNonCommLongShort = number_format($NonComm_Positions_Long_All / $NonComm_Positions_Short_All, 1, ',', '.');
                            $DivNonCommShortLong = number_format($NonComm_Positions_Short_All / $NonComm_Positions_Long_All, 1, ',', '.');


                            //////////////////////////////////////////////////////////
                            //formatação condicional do NonComm
                            //LONG
                            $class_NonLong = '';
                            if ($PorcNonCommLong >= 50 && $PorcNonCommLong < 60):
                                $class_NonLong = 'bg-yellow-saffron';
                            elseif ($PorcNonCommLong >= 60 && $PorcNonCommLong < 70):
                                $class_NonLong = 'bg-yellow-crusta';
                            elseif ($PorcNonCommLong >= 70 && $PorcNonCommLong < 80):
                                $class_NonLong = 'bg-green-turquoise';
                            elseif ($PorcNonCommLong >= 80):
                                $class_NonLong = 'bg-green-jungle';
                            endif;

                            //Short
                            $class_NonShort = '';
                            if ($PorcNonCommShort >= 50 && $PorcNonCommShort < 60):
                                $class_NonShort = 'bg-yellow-saffron';
                            elseif ($PorcNonCommShort >= 60 && $PorcNonCommShort < 70):
                                $class_NonShort = 'bg-yellow-crusta';
                            elseif ($PorcNonCommShort >= 70 && $PorcNonCommShort < 80):
                                $class_NonShort = 'bg-green-turquoise';
                            elseif ($PorcNonCommShort >= 80):
                                $class_NonShort = 'bg-green-jungle';
                            endif;

                            //NET
                            $class_NonNet = '';
                            if ($NetNonComm >= $nonNet):
                                $class_NonNet = 'bg-green-jungle';
                            else:
                                $class_NonNet = 'bg-red';
                            endif;
                            // end da formatação condicional NonComm
                            ///////////////////////////////////////////////////////////////////////////

                            $TotalComm = $Comm_Positions_Long_All + $Comm_Positions_Short_All;
                            $PorcCommLong = number_format(($Comm_Positions_Long_All * 100) / $TotalComm);
                            $PorcCommShort = number_format(($Comm_Positions_Short_All * 100) / $TotalComm);
                            $NetComm = $Comm_Positions_Long_All - $Comm_Positions_Short_All;
                            $DifNet = $NetNonComm - $NetComm;

                            /////////////////////////////////////////////////////////////////////////////
                            //formatação condicional do Comm
                            //Long
                            $class_long = '';
                            if ($PorcCommLong >= 50 && $PorcCommLong < 60):
                                $class_long = 'bg-yellow-saffron';
                            elseif ($PorcCommLong >= 60 && $PorcCommLong < 70):
                                $class_long = 'bg-yellow-crusta';
                            elseif ($PorcCommLong >= 70 && $PorcCommLong < 80):
                                $class_long = 'bg-green-turquoise';
                            elseif ($PorcCommLong >= 80):
                                $class_long = 'bg-green-jungle';
                            endif;

                            //Short
                            $class_short = '';
                            if ($PorcCommShort >= 50 && $PorcCommShort < 60):
                                $class_short = 'bg-yellow-saffron';
                            elseif ($PorcCommShort >= 60 && $PorcCommShort < 70):
                                $class_short = 'bg-yellow-crusta';
                            elseif ($PorcCommShort >= 70 && $PorcCommShort < 80):
                                $class_short = 'bg-green-turquoise';
                            elseif ($PorcCommShort >= 80):
                                $class_short = 'bg-green-jungle';
                            endif;

                            //NET
                            $class_Net = '';
                            if ($NetComm >= $cNet):
                                $class_cNet = 'bg-green-jungle';
                            else:
                                $class_cNet = 'bg-red';
                            endif;

                            //DIF
                            $class_cDif = '';
                            if ($DifNet >= $cDif):
                                $class_cDif = 'bg-green-jungle';
                            else:
                                $class_cDif = 'bg-red';
                            endif;
                            // end da formatação condicional Comm
                            /////////////////////////////////////////////////////////////////
                            ?>
                            <tr>
                                <td> <?= date('d/m/Y', strtotime($indice_data)); ?> </td>
                                <td> <?= $NonComm_Positions_Long_All; ?> </td>
                                <td> <?= $NonComm_Positions_Short_All; ?> </td>
                                <td> <?= $TotalNonComm; ?> </td>
                                <td class="<?= $class_NonLong; ?>"> <?= $PorcNonCommLong ?>% </td>
                                <td class="<?= $class_NonShort; ?>"> <?= $PorcNonCommShort ?>% </td> </td>
                                <td class="<?= $class_NonNet; ?>"> <?= $NetNonComm = $NonComm_Positions_Long_All - $NonComm_Positions_Short_All; ?> </td>
                                <td> <?= $DivNonCommLongShort; ?>:1 </td>
                                <td> <?= $DivNonCommShortLong; ?>:1 </td>
                                <td>  </td>
                                <td> <?= $Comm_Positions_Long_All; ?> </td>
                                <td> <?= $Comm_Positions_Short_All; ?> </td>
                                <td> <?= $TotalComm; ?> </td>
                                <td class="<?= $class_long; ?>"> <?= $PorcCommLong ?>% </td>
                                <td class="<?= $class_short; ?>"> <?= $PorcCommShort ?>% </td> </td>
                                <td class="<?= $class_cNet; ?>"> <?= $NetComm; ?> </td>
                                <td class="<?= $class_cDif; ?>"> <?= $DifNet; ?> </td>
                            </tr>

                            <?php
                        endforeach;
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- END tabela indice -->

    <div class="row">
        <div class="col-md-12">
            <iframe id="widgetMataf" style="border: none; overflow:hidden; background-color: transparent; height: 400px; width: 1200px" src="https://www.mataf.net/pt/widget/currencyindex"></iframe> 
        </div>
    </div>
    <?php
    //////////////////////// grafico DIF /////////////////////////////
    $i = 0;
    $Read->ExeRead("tp_indice", "WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    foreach ($Read->getResult() as $indices):
        extract($indices);
        $Dados['data'][$i] = "'" . date("d/m/Y", strtotime($indice_data)) . "'";

        $NetNonComm = $NonComm_Positions_Long_All - $NonComm_Positions_Short_All;
        $NetComm = $Comm_Positions_Long_All - $Comm_Positions_Short_All;
        $Dados['dif'][$i] = $NetNonComm - $NetComm;

        ///Calcular a media dos ultimos 12 semanas     
        $dias = 7 * 12;

        $data_dif_ini = $indice_data;
        $data_dif_fim = date('Y-m-d', strtotime("-{$dias} day", strtotime($data_dif_ini)));
        $ReadDif = new Read;
        $ReadDif->FullRead("SELECT (NonComm_Positions_Long_All - NonComm_Positions_Short_All) - (Comm_Positions_Long_All - Comm_Positions_Short_All) as DIF FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC LIMIT 12", "codigo={$moedid}&data_ini={$data_dif_ini}&data_fim={$data_dif_fim}");
        unset($arrDif);
        foreach ($ReadDif->getResult() as $DIFS):
            $arrDif[] = $DIFS['DIF'];
        endforeach;
        $Dados['dif_media'][$i] = array_sum($arrDif) / 12;
        $i++;

    endforeach;

    $difDat = implode(', ', array_reverse($Dados['data']));
    $difVal = implode(', ', array_reverse($Dados['dif']));
    $difMed = implode(', ', array_reverse($Dados['dif_media']));
    /////////////////////////// Fim do gráfico DIF///////////////////////
    //////////////////////// grafico Normalizado /////////////////////////////
    $ReadNormalizado = new Read;
    $ReadNormalizado->FullRead("SELECT NonComm_Positions_Long_All - NonComm_Positions_Short_All as NetNonComm, Comm_Positions_Long_All - Comm_Positions_Short_All as NetComm FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    //maximo e minimo
    foreach ($ReadNormalizado->getResult() as $mm):
        $arrayNonComm[] = $mm['NetNonComm'];
        $arrayComm[] = $mm['NetComm'];
    endforeach;

    $maxNetNonComm = max($arrayNonComm);
    $minNetNonComm = min($arrayNonComm);
    $maxNetComm = max($arrayComm);
    $minNetComm = min($arrayComm);

    foreach ($ReadNormalizado->getResult() as $normalizado):
        extract($normalizado);
        $Dados['NetPosicNonComm'][] = round(($NetNonComm - $minNetNonComm) / ($maxNetNonComm - $minNetNonComm) * 100);
        $Dados['NetPosicComm'][] = round(($NetComm - $minNetComm) / ($maxNetComm - $minNetComm) * 100);
    endforeach;

    $nNetNonCommStr = implode(', ', array_reverse($Dados['NetPosicNonComm']));
    $nNetCommStr = implode(', ', array_reverse($Dados['NetPosicComm']));
    /////////////////////////// Fim do gráfico Normalizado///////////////////////
    //
    //
    //
    //
    //
    //////////////////////// grafico Moviem index /////////////////////////////
    $ReadIndex = new Read;
    $ReadIndex->FullRead("SELECT max((NonComm_Positions_Long_All - NonComm_Positions_Short_All) / (Open_Interest_All - NonComm_Postions_Spread_All)) as maxCoverOi, min((NonComm_Positions_Long_All - NonComm_Positions_Short_All) / (Open_Interest_All - NonComm_Postions_Spread_All)) as minCoverOi FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    extract($ReadIndex->getResult()[0]);

    $ReadIndex->FullRead("SELECT indice_data, (NonComm_Positions_Long_All - NonComm_Positions_Short_All) / (Open_Interest_All - NonComm_Postions_Spread_All) as CoverOi FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    $i = 0;

    foreach ($ReadIndex->getResult() as $Index):
        extract($Index);
        $Dados['oi'][] = $CoverOi;
        $Moviment = number_format(($CoverOi - $minCoverOi) / ($maxCoverOi - $minCoverOi) * 100,2);
        $Dados['mov'][] = $Moviment;
        $Dados['min'][] = $minCoverOi;
        $Dados['max'][] = $maxCoverOi;
        ///Calcular a media dos ultimos 6 semanas     
        $dias = 7 * 6;

        $data_ind_ini = $indice_data;
        $data_ind_fim = date('Y-m-d', strtotime("-{$dias} day", strtotime($data_ind_ini)));

        $ReadInd = new Read;
        $ReadInd->FullRead("SELECT max((NonComm_Positions_Long_All - NonComm_Positions_Short_All) / (Open_Interest_All - NonComm_Postions_Spread_All)) as maxIndex, min((NonComm_Positions_Long_All - NonComm_Positions_Short_All) / (Open_Interest_All - NonComm_Postions_Spread_All)) as minIndex FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ind_ini}&data_fim={$data_ind_fim}");
        extract($ReadInd->getResult()[0]);

        $ReadInd->FullRead("SELECT (NonComm_Positions_Long_All - NonComm_Positions_Short_All) / (Open_Interest_All - NonComm_Postions_Spread_All) as mIndex FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ind_ini}&data_fim={$data_ind_fim}");
        unset($arrInd);
        $arrInd = array();
        foreach ($ReadInd->getResult() as $Index):
            extract($Index);
            $arrInd[] = round(($mIndex - $minIndex) / ($maxIndex - $minIndex) * 100);
        endforeach;
        $moIndex = array_sum($arrInd) / 6;


        $Dados['CoverOi'][] = $Moviment - $moIndex;
    endforeach;

    $CoverOiStr = implode(', ', array_reverse($Dados['CoverOi']));
    /////////////////////////// Fim do gráfico Index///////////////////////
    //
    //
    //
    //
    //
    //
    //
    //////////////////////// grafico Moviem FlipNC /////////////////////////////
    $ReadFlipNc = new Read;
    $ReadFlipNc->FullRead("SELECT max(Pct_of_OI_NonComm_Long_All - Pct_of_OI_NonComm_Short_All) as maxFlip, min(Pct_of_OI_NonComm_Long_All - Pct_of_OI_NonComm_Short_All) as minFlip FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    extract($ReadFlipNc->getResult()[0]);

    $ReadFlipNc->FullRead("SELECT Pct_of_OI_NonComm_Long_All - Pct_of_OI_NonComm_Short_All as Flip FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    $i = 0;
    foreach ($ReadFlipNc->getResult() as $FlipNc):
        extract($FlipNc);
        $Dados['FlipNc'][] = round(($Flip - $minFlip) / ($maxFlip - $minFlip) * 100);
    endforeach;

    $FlipNcStr = implode(', ', array_reverse($Dados['FlipNc']));
    /////////////////////////// Fim do gráfico FlipNC///////////////////////
    //////////////////////// grafico Moviem FlipNC /////////////////////////////
    $ReadM1 = new Read;
    $ReadM1->FullRead("SELECT max(Pct_of_OI_NonComm_Long_All - Pct_of_OI_NonComm_Short_All) as maxFlip, min(Pct_of_OI_NonComm_Long_All - Pct_of_OI_NonComm_Short_All) as minFlip FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    extract($ReadM1->getResult()[0]);

    $ReadM1->FullRead("SELECT Pct_of_OI_NonComm_Long_All - Pct_of_OI_NonComm_Short_All as Flip FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    $i = 0;
    foreach ($ReadM1->getResult() as $M1):
        extract($M1);
        $Dados['M1'][] = round(($Flip - $minFlip) / ($maxFlip - $minFlip) * 100);
    endforeach;

    $FlipNcStr = implode(', ', array_reverse($Dados['FlipNc']));
    /////////////////////////// Fim do gráfico FlipNC///////////////////////
    //////////////////////// grafico Normalizado /////////////////////////////
    $ReadPrin = new Read;
    $ReadPrin->FullRead("SELECT max(NonComm_Positions_Long_All - NonComm_Positions_Short_All) as maxPNetNonComm, min(NonComm_Positions_Long_All - NonComm_Positions_Short_All) as minPNetNonComm FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    extract($ReadPrin->getResult()[0]);

    $ReadPrin->FullRead("SELECT NonComm_Positions_Long_All - NonComm_Positions_Short_All as NetNonComm FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    foreach ($ReadPrin->getResult() as $liquidez):
        extract($liquidez);
        $Dados['NetPrinNonComm'][] = round($NetNonComm);
        $Dados['NetPrinNonCommNorm'][] = round(($NetNonComm - $minNetNonComm) / ($maxNetNonComm - $minNetNonComm) * 100);
    endforeach;

    $moeda_base = '098662';
    $ReadBase = new Read;
    $ReadBase->FullRead("SELECT max(NonComm_Positions_Long_All - NonComm_Positions_Short_All) as maxBNetNonComm, min(NonComm_Positions_Long_All - NonComm_Positions_Short_All) as minBNetNonComm FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moeda_base}&data_ini={$data_ini}&data_fim={$data_fim}");
    extract($ReadBase->getResult()[0]);

    $ReadBase->FullRead("SELECT NonComm_Positions_Long_All - NonComm_Positions_Short_All as NetNonComm FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moeda_base}&data_ini={$data_ini}&data_fim={$data_fim}");
    foreach ($ReadBase->getResult() as $liquidez):
        extract($liquidez);
        $Dados['NetBaseNonComm'][] = round($NetNonComm);
        $Dados['NetBaseNonCommNorm'][] = round(($NetNonComm - $minBNetNonComm) / ($maxBNetNonComm - $minBNetNonComm) * 100);
    endforeach;

    for ($i = 0; $i < count($Dados['NetBaseNonComm']); $i++) {
        $Dados['NetNonCommMoed'][] = $Dados['NetPrinNonComm'][$i] - $Dados['NetBaseNonComm'][$i];
        $Dados['NetNonCommMoedNorm'][] = $Dados['NetPrinNonCommNorm'][$i] - $Dados['NetBaseNonCommNorm'][$i];
    }

    $NetNonCommStr = implode(', ', array_reverse($Dados['NetNonCommMoed']));
    $NetNonCommNormStr = implode(', ', array_reverse($Dados['NetNonCommMoedNorm']));
    /////////////////////////// Fim do gráfico Normalizado///////////////////////
    /////////////////////////////////////////////////////////////////////////////
    //////////////////////// grafico volume /////////////////////////////
    $ReadPrin = new Read;

    $ReadPrin->FullRead("SELECT NonComm_Positions_Long_All + NonComm_Postions_Spread_All + Comm_Positions_Long_All + NonRept_Positions_Long_All as Aberto, NonComm_Positions_Long_All + NonComm_Positions_Short_All as Volume  FROM tp_indice WHERE CFTC_Contract_Market_Code = :codigo AND indice_data BETWEEN :data_fim AND :data_ini ORDER BY indice_data DESC", "codigo={$moedid}&data_ini={$data_ini}&data_fim={$data_fim}");
    foreach ($ReadPrin->getResult() as $liquidez):
        extract($liquidez);
        $Dados['Volume'][] = $Volume;
        $Dados['Aberto'][] = $Aberto;
    endforeach;

    $VolumeStr = implode(', ', array_reverse($Dados['Volume']));
    $AbertoStr = implode(', ', array_reverse($Dados['Aberto']));
    /////////////////////////// Fim do gráfico Normalizado///////////////////////
//    echo '<pre>';
//    print_r($Dados['min']);
//    print_r($Dados['max']);
//    print_r($Dados['mov']);
//    print_r($Dados['oi']);
//    echo '</pre>';
    ?>

    <div class="row">
        <div class="col-md-12">
            <div id="dif"></div>
        </div>
    </div>
    <hr>
    <div class="row">
        <div class="col-md-12">
            <div id="normalizado"></div>
        </div>
    </div>
    <hr>
    <div class="row">
        <div class="col-md-12">
            <div id="index"></div>
        </div>
    </div>
    <hr>
    <div class="row">
        <div class="col-md-12">
            <div id="flip"></div>
        </div>
    </div>
    <hr>
    <div class="row">
        <div class="col-md-12">
            <div id="moedas"></div>
        </div>
    </div>
    <hr>
    <div class="row">
        <div class="col-md-12">
            <div id="volume"></div>
        </div>
    </div>

    <script src="__jsc/highcharts/code/highcharts.js"></script>
    <script src="__jsc/highcharts/code/modules/data.js"></script>
    <script src="__jsc/highcharts/code/modules/series-label.js"></script>
    <script src="__jsc/highcharts/code/modules/exporting.js"></script>
    <script src="__jsc/highcharts/code/modules/export-data.js"></script>


    <script type="text/javascript">

                    Highcharts.setOptions({
                        colors: ['#3faba4', '#c49f47', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263']
                    });

                    Highcharts.chart('dif', {
                        chart: {
                            backgroundColor: '#00000'
                        },
                        title: {
                            text: 'Distância da média em função contrato'
                        },

                        credits: {
                            enabled: false
                        },

                        xAxis: {
                            categories: [<?= $difDat; ?>],
                            tickmarkPlacement: 'on',
                            title: {
                                enabled: false
                            }
                        },
                        yAxis: {
                            title: {
                                text: ''
                            }
                        },

                        legend: {
                            align: 'center',
                            verticalAlign: 'bottom',
                            borderWidth: 0
                        },

                        tooltip: {
                            shared: true,
                            crosshairs: true
                        },

                        series: [{
                                name: 'Diferença',
                                data: [<?= $difVal; ?>]
                            }, {
                                name: 'Média',
                                data: [<?= $difMed; ?>]
                            }]
                    });

                    Highcharts.chart('normalizado', {
                        chart: {
                            backgroundColor: '#000000'
                        },
                        title: {
                            text: 'Net Position Normalizado'
                        },

                        credits: {
                            enabled: false
                        },

                        xAxis: {
                            categories: [<?= $difDat; ?>],
                            tickmarkPlacement: 'on',
                            title: {
                                enabled: false
                            }
                        },
                        yAxis: {
                            title: {
                                text: ''
                            }
                        },

                        legend: {
                            align: 'center',
                            verticalAlign: 'bottom',
                            borderWidth: 0
                        },

                        tooltip: {
                            shared: true,
                            crosshairs: true
                        },

                        series: [{
                                name: 'Net_Posi_NC',
                                data: [<?= $nNetNonCommStr; ?>]
                            }, {
                                name: 'Net_posi_CC',
                                data: [<?= $nNetCommStr; ?>]
                            }]
                    });

                    Highcharts.chart('index', {
                        chart: {
                            backgroundColor: '#000000',
                            type: 'column'
                        },
                        title: {
                            text: 'Moviment Index'
                        },
                        xAxis: {
                            categories: [<?= $difDat; ?>]
                        },
                        credits: {
                            enabled: false
                        },
                        series: [{
                                name: 'Moviment',
                                data: [<?= $CoverOiStr; ?>]
                            }]
                    });

                    Highcharts.chart('flip', {
                        chart: {
                            backgroundColor: '#000000'
                        },
                        title: {
                            text: 'Flip NC'
                        },

                        credits: {
                            enabled: false
                        },

                        xAxis: {
                            categories: [<?= $difDat; ?>],
                            tickmarkPlacement: 'on',
                            title: {
                                enabled: false
                            }
                        },
                        yAxis: {
                            title: {
                                text: ''
                            }
                        },

                        legend: {
                            align: 'center',
                            verticalAlign: 'bottom',
                            borderWidth: 0
                        },

                        tooltip: {
                            shared: true,
                            crosshairs: true
                        },

                        series: [{
                                name: 'Flip_NC',
                                data: [<?= $FlipNcStr; ?>]
                            }]
                    });

                    Highcharts.chart('moedas', {
                        chart: {
                            backgroundColor: '#000000'
                        },
                        title: {
                            text: 'Moedas'
                        },

                        credits: {
                            enabled: false
                        },

                        xAxis: {
                            categories: [<?= $difDat; ?>],
                            tickmarkPlacement: 'on',
                            title: {
                                enabled: false
                            }
                        },
                        yAxis: [{// Primary yAxis
                                labels: {
                                    format: '{value}%',
                                    style: {
                                        color: Highcharts.getOptions().colors[1]
                                    }
                                },
                                title: {
                                    text: 'Normalizado',
                                    style: {
                                        color: Highcharts.getOptions().colors[1]
                                    }
                                }
                            }, {// Secondary yAxis
                                title: {
                                    text: 'Liquidez',
                                    style: {
                                        color: Highcharts.getOptions().colors[0]
                                    }
                                },
                                labels: {
                                    format: '{value} ',
                                    style: {
                                        color: Highcharts.getOptions().colors[0]
                                    }
                                },
                                opposite: true
                            }],

                        legend: {
                            align: 'center',
                            verticalAlign: 'bottom',
                            borderWidth: 0
                        },

                        tooltip: {
                            shared: true,
                            crosshairs: true
                        },

                        series: [{
                                name: 'Liquidez',
                                type: 'spline',
                                yAxis: 1,
                                data: [<?= $NetNonCommStr; ?>],
                                tooltip: {
                                    valueSuffix: ' '
                                }
                            },
                            {
                                name: 'Normarlizado',
                                type: 'spline',
                                data: [<?= $NetNonCommNormStr; ?>],
                                tooltip: {
                                    valueSuffix: '%'
                                }
                            }]
                    });

                    Highcharts.chart('volume', {
                        chart: {
                            backgroundColor: '#000000'
                        },
                        title: {
                            text: 'Contratos em abertos em função volume'
                        },

                        credits: {
                            enabled: false
                        },

                        xAxis: {
                            categories: [<?= $difDat; ?>],
                            tickmarkPlacement: 'on',
                            title: {
                                enabled: false
                            }
                        },
                        yAxis: [{// Primary yAxis
                                labels: {
                                    format: '{value}',
                                    style: {
                                        color: Highcharts.getOptions().colors[1]
                                    }
                                },
                                title: {
                                    text: 'Abertos',
                                    style: {
                                        color: Highcharts.getOptions().colors[1]
                                    }
                                }
                            }],

                        legend: {
                            align: 'center',
                            verticalAlign: 'bottom',
                            borderWidth: 0
                        },

                        tooltip: {
                            shared: true,
                            crosshairs: true
                        },

                        series: [{
                                name: 'Volumes',
                                type: 'column',
                                data: [<?= $VolumeStr; ?>],
                                tooltip: {
                                    valueSuffix: ' '
                                }
                            },
                            {
                                name: 'Abertos',
                                type: 'spline',
                                data: [<?= $AbertoStr; ?>],
                                tooltip: {
                                    valueSuffix: ' '
                                }
                            }]
                    });

    </script>
<?php
endif;
?>

<script>
    function filtro() {
        var moeda = $("#campo_moeda").val();
        var periodo = $("#campo_periodo").val();



        if (moeda == '') {
            console.log('moeda vazia');
        } else if (periodo == '') {
            console.log('periodo vazia');
        } else {
            window.location.href = "painel.php?exe=indice/index&moedid=" + moeda + "&perid=" + periodo;
        }
    }
</script>