<?php

/**

 * Created by PhpStorm.

 * User: brycemoral

 * Date: 6/16/16

 * Time: 9:22 PM

 */







// oandaAPI is an that has methods to talk to the OANDA API

class oandaAPI {

        public $accountId;

        public $accountName;

        public $balance;

        public $unrealizedPl;

        public $marginUsed;

        public $marginAvail;

        public $openTrades;

        public $openTrade;

        public $openOrders;

        public $marginRate;

        public $homecurr;

    function __construct(){



    }



    public $tradePlaced = false;

    // Retrieves basic account information based on accountNumber

    function retrieveAccount($accountNumber) {

         $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/".$accountNumber);

        $header = array();

        $header[] = 'Content-type: application/json';

         $header[] = 'Authorization: Bearer 715ebde2682f2dc1c9f9334820db9207-baaa61ac5440c676218caa9d2bae5d9a';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        // Store the values returned from cURL execution

        $this->accountId = $result['accountId'];

        $this->accountName = $result['accountName'];

        $this->balance = $result['account']['balance'];

        $this->unrealizedPl = $result['account']['unrealizedPL'];

        $this->marginUsed = $result['account']['marginUsed'];

        $this->marginAvail = $result['account']['marginAvailable'];

        $this->openTrades = $result['account']['openTradeCount'];

        $this->openOrders = $result['account']['pendingOrderCount'];

        $this->marginRate = $result['account']['marginRate'];

        $this->homecurr = $result['account']['currency'];

        

        return $result;



    }

	function retrieveNews($accountNumber, $pair)

	{

	$ch = curl_init("https://api-fxtrade.oanda.com/labs/v1/calendar?instrument=EUR_USD&period=2592000");

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        // Store the values returned from cURL execution



        return $result;

//https://api-fxtrade.oanda.com/labs/v1/calendar?instrument=EUR_USD&period=2592000" -H "Authorization: Bearer <access-token>"	

	}

    // Retrieve information for Open Trades

    function retrieveTrades($accountNumber) {

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/".$accountNumber."/openTrades");

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer 715ebde2682f2dc1c9f9334820db9207-baaa61ac5440c676218caa9d2bae5d9a';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        // Store the values returned from cURL execution

        $this->openTrade = $result['trades'];

        return $result['trades'];

    }



    //NOTE: need to change back to user_account variable

    public function accountActivity()

    {

        $listOfCurrencies = "EUR_USD%2CEUR_JPY%2CEUR_GBP%2CUSD_JPY%2CUSD_CHF%2CUSD_CAD%2CGBP_USD%2CGBP_JPY%2CAUD_USD%2CNZD_USD";

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/trades?" . $listOfCurrencies);

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        print_r($result);

    }



    //NOTE: need to change back to user_account variable

    public function todaysProfit($userid)

    {

        $transactions = $this->getTransactions($userid);

        $dayProfit = 0;

        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {

                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                            $date = explode('T', $a['time']);

                            $start_date = new DateTime($date[0]);

                            $since_start = $start_date->diff(new DateTime('now'));

                            if($since_start->days < 1)

                            {

                                $dayProfit += $a['tradesClosed'][0]['realizedPL']; 

                            }



                        }

                        

                    } 

                }

            }

        }

        return $dayProfit;

    }

    //NOTE: need to change back to user_account variable

    public function weekProfit($uid)

    {

        $transactions = $this->getTransactions($uid);

        $weekProfit = 0;

        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {

                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                            $date = explode('T', $a['time']);

                            $start_date = new DateTime($date[0]);

                            $since_start = $start_date->diff(new DateTime('now'));

                            if($since_start->days <= 7)

                            {

                                $weekProfit += $a['tradesClosed'][0]['realizedPL']; 

                            }

                        

                        }

                        

                    } 

                }

            }

        }

        return $weekProfit;

    }



     public function month_profit($uid)

    {

        $transactions = $this->getTransactions($uid);

        $monthProfit = 0;

        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {

                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                            $date = explode('T', $a['time']);

                            $start_date = new DateTime($date[0]);

                            $since_start = $start_date->diff(new DateTime('now'));

                            if($since_start->days <= 31)

                            {

                                $monthProfit += $a['tradesClosed'][0]['realizedPL']; 

                            }

                        

                        }

                        

                    } 

                }

            }

        }

        return $monthProfit;

    }





    public function halfyear_profit($uid)

    {

        $transactions = $this->getTransactions($uid);

        $monthProfit = 0;

        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {

                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                            $date = explode('T', $a['time']);

                            $start_date = new DateTime($date[0]);

                            $since_start = $start_date->diff(new DateTime('now'));

                            if($since_start->days <= 182)

                            {

                                $monthProfit += $a['tradesClosed'][0]['realizedPL']; 

                            }

                        

                        }

                        

                    } 

                }

            }

        }

        return $monthProfit;

    }







    public function year_profit($uid)

    {

        $transactions = $this->getTransactions($uid);

        $monthProfit = 0;

        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {

                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                            $date = explode('T', $a['time']);

                            $start_date = new DateTime($date[0]);

                            $since_start = $start_date->diff(new DateTime('now'));

                            if($since_start->days <= 365)

                            {

                                $monthProfit += $a['tradesClosed'][0]['realizedPL']; 

                            }

                        

                        }

                        

                    } 

                }

            }

        }

        return $monthProfit;

    }









     public function total_profit($uid)

    {

        $transactions = $this->getTransactions($uid);

        $monthProfit = 0;

        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {

                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                           $monthProfit += $a['tradesClosed'][0]['realizedPL']; 

                        

                        }

                        

                    } 

                }

            }

        }

        return $monthProfit;

    }













   	public function completeReport($userid)

   	{



   		$transactions = $this->getTransactions($userid);



   		$transactionReport = array();



        foreach($transactions as $t)

        {

            // print_r($t);

            foreach($t as $a)

            {



                foreach($a as $d)

                {

                        // print_r($a);

                    if($a['type'] == "ORDER_FILL"){

                        // echo $

                        

                        if($a['reason'] == "MARKET_ORDER_TRADE_CLOSE"){

                            

                          	$weekProfit = $a['tradesClosed'][0]['realizedPL'];



                            array_push($transactionReport, $weekProfit);  



                        }

                        

                    } 

                }

            }

        }



        return $transactionReport;

   	}































    //NOTE: need to change back to user_account variable

    public function totalAccountProfit($accountNumber)

    {

        $listOfCurrencies = "EUR_USD%2CEUR_JPY%2CEUR_GBP%2CUSD_JPY%2CUSD_CHF%2CUSD_CAD%2CGBP_USD%2CGBP_JPY%2CAUD_USD%2CNZD_USD";

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/".$accountNumber."/trades?" . $listOfCurrencies);

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        print_r($result);

    }

    //NOTE: need to change back to user_account variable

    public function monthProfit()

    {

        $listOfCurrencies = "EUR_USD%2CEUR_JPY%2CEUR_GBP%2CUSD_JPY%2CUSD_CHF%2CUSD_CAD%2CGBP_USD%2CGBP_JPY%2CAUD_USD%2CNZD_USD";

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/trades?" . $listOfCurrencies);

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        print_r($result);

    }

    //NOTE: need to change back to user_account variable

    public function yearProfit()

    {

        $listOfCurrencies = "EUR_USD%2CEUR_JPY%2CEUR_GBP%2CUSD_JPY%2CUSD_CHF%2CUSD_CAD%2CGBP_USD%2CGBP_JPY%2CAUD_USD%2CNZD_USD";

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/trades?" . $listOfCurrencies);

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        print_r($result);

    }











    //NOTE: need to change back to user_account variable

    public function retrieveUserProfile($uid) {

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/".$uid."/summary");

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        return $result;

    }

    



    public function placeMarketTrade($accountNumber, $currency, $tradeDirection, $units){

        $direction = "buy";

        $amountBet = $units;

        if($tradeDirection == "S")

        {

            $direction = "sell";

            $amountBet = $units;

        }

        else if($tradeDirection == "SS"){

            $direction = "sell";

            $amountBet = $units * 2;

        }

        else if($tradeDirection == "SB"){

            $direction = "buy";

            $amountBet = $units * 2;

        }

        $ch = curl_init("https://api-fxtrade.oanda.com/v1/accounts/".$accountNumber."/orders");

        $type = "market";

        $postData = "instrument=" . $currency . "&units=" . $amountBet . "&side=" . $direction . "&type=" . $type;

        $header = array();

        $header[] = 'Content-type: application/x-www-form-urlencoded';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        // Store the values returned from cURL execution

        $this->tradePlaced = true;

    }

    

        public function closeTrades($accountNumber) {

        $openTrades = $this->retrieveTrades($accountNumber);

        print_r($openTrades);

        foreach($openTrades as $trade){

        $tradeId = $trade['id'];

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/trades/" . $tradeId . "/close");

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        //print_r(json_decode($result));

        }

    }

    public function closeIndividualTrade($accountNumber, int $tradeIdInput) {

        $openTrades = $this->retrieveTrades($accountNumber);

        print_r($openTrades);

        foreach($openTrades as $trade){

            if($tradeIdInput != $trade['id']){continue;}

        $tradeId = $trade['id'];

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/trades/" . $tradeId . "/close");

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        //print_r(json_decode($result));

        }

    }

    public function modifyIndividualRecord($accountNumber, int $tradeIdInput, $stop_loss, $take_profit) {

        $openTrades = $this->retrieveTrades($accountNumber);

        $postData = array();

        $postData['takeProfit']['price'] = $take_profit;

        $postData['takeProfit']['timeInForce'] = "GTC";

        $postData['stopLoss']['price'] = $stop_loss;

        $postData['takeProfit']['timeInForce'] = "GTC";

        $postData = json_encode($postData);

        foreach($openTrades as $trade){

            if($tradeIdInput != $trade['id']){continue;}

            $tradeId = $trade['id'];

            $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/001-001-414778-001/trades/" . $tradeId . "/orders");

            $header = array();

            $header[] = 'Content-type: application/json';

            $header[] = 'Authorization: Bearer c143ece96a9cb2ce9dc6ecdbaf844523-77cf55b79018d06cf3396c90855d06be';

            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $result = curl_exec($ch);

        }

    }







    public function getTransactions($userid) {

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/".$userid."/transactions/");

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer 715ebde2682f2dc1c9f9334820db9207-baaa61ac5440c676218caa9d2bae5d9a';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        $maxId = $result['count'];

        $result = array();

        $ch = curl_init("https://api-fxtrade.oanda.com/v3/accounts/".$userid."/transactions/idrange?from=1&to=" . $maxId);

        $header = array();

        $header[] = 'Content-type: application/json';

        $header[] = 'Authorization: Bearer 715ebde2682f2dc1c9f9334820db9207-baaa61ac5440c676218caa9d2bae5d9a';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        $result = json_decode($result, true);

        return $result;

    }





}