#include "moving_averages.hh"

MovingAverages::MovingAverages()
    : dataValid_(false)
{
    dataRequest_.append("PRICE");
    dataRequest_.append("EMA10");
    dataRequest_.append("EMA20");
}

DataRequest MovingAverages::requestedData()
{
    return dataRequest_;
}

bool MovingAverages::tradeData(const TradeData& data)
{
    tradeData_ = data;

    if (dialog_ && dialog_->isVisible())
        dialog_->setData(tradeData_);

    dataValid_ = tradeData_.validate(dataRequest_);
    return dataValid_;
}

OrderVector MovingAverages::makeDecision()
{
    OrderVector decision;

    if (!dataValid_)
        return decision;

    if (tradeData_.orderCount() > 0) {
        int ticket = tradeData_.order(0).ticket;
        double price = tradeData_.candle(0).close();

        double orderOpen = tradeData_.order(0).openPrice;
        double takeProfit = tradeData_.order(0).takeProfit;
        double profitPoint = (orderOpen + takeProfit) / 2;

        if ((tradeData_.order(0).type == "BUY" && price > profitPoint) ||
            (tradeData_.order(0).type == "SELL" && price < profitPoint))
        {
            decision.push_back(Order::modify(ticket, 150, 150));

            if (tradeData_.order(0).lots > 0.06)
                decision.push_back(Order::close(ticket, 0.05, 3));
        }

        return decision;
    }

    double EMA10_0 = tradeData_.value("EMA10", 0).second;
    double EMA10_1 = tradeData_.value("EMA10", 1).second;
    double EMA20_0 = tradeData_.value("EMA20", 0).second;
    double EMA20_1 = tradeData_.value("EMA20", 1).second;

    if (EMA10_1 > EMA20_1 && EMA10_0 < EMA20_0)
        decision.push_back(Order::send("SELL", 0.1, 3, 300, 300));
    else if (EMA10_1 < EMA20_1 && EMA10_0 > EMA20_0)
        decision.push_back(Order::send("BUY", 0.1, 3, 300, 300));

    return decision;
}

void MovingAverages::onClientDoubleClicked()
{
    if (!dialog_)
        dialog_.reset(new ControlDialog());

    dialog_->setData(tradeData_);
    dialog_->show();
}

void MovingAverages::decisionStatus(const OrderVector& status)
{
    decisionStatus_ = status;
}
