#include "sierrachart.h"

SCDLLName("SimpleBacktest")

SCSFExport scsf_Backtest_Simple(SCStudyInterfaceRef sc)
{
	SCInputRef holdBars_Input = sc.Input[0];

	if (sc.SetDefaults)
	{
		sc.GraphName = "Backtest_Simple";

		holdBars_Input.Name = "holdBars";
		holdBars_Input.SetInt(120);

		sc.AutoLoop = 1;
		sc.GraphRegion = 0;

		sc.AllowMultipleEntriesInSameDirection = false;
		sc.MaximumPositionAllowed = 10;
		sc.SupportReversals = false;

		// This is false by default. Orders will go to the simulation system always.
		sc.SendOrdersToTradeService = false;

		sc.AllowOppositeEntryWithOpposingPositionOrOrders = false;

		// "It is not necessary to set sc.SupportAttachedOrdersForTrading to TRUE (1) for these Attached Orders to be used."
		// sc.SupportAttachedOrdersForTrading = false;

		sc.CancelAllOrdersOnEntriesAndReversals = true;
		sc.AllowEntryWithWorkingOrders = false;
		sc.CancelAllWorkingOrdersOnExit = false;

		// Only 1 trade for each Order Action type is allowed per bar.
		sc.AllowOnlyOneTradePerBar = true;

		//This needs to be set to true when a trading study uses trading functions.
		sc.MaintainTradeStatisticsAndTradesData = true;

		//sc.MaintainReferenceToOtherChartsForPersistentVariables = 1;

		sc.ReceiveKeyboardKeyEvents = 1;
		//sc.ReceivePointerEvents = ACS_RECEIVE_POINTER_EVENTS_ALWAYS;
		return;
	}
	

	if (sc.IsFullRecalculation)
		return;

	SCString msg;

	s_SCNewOrder NewOrder;
	NewOrder.OrderQuantity = 1;
	NewOrder.OrderType = SCT_ORDERTYPE_MARKET;
	NewOrder.TimeInForce = SCT_TIF_GOOD_TILL_CANCELED;

	if (sc.GetBarHasClosedStatus() == BHCS_BAR_HAS_NOT_CLOSED)
		return;

	int& entryBarIdx = sc.GetPersistentInt(3023);


	s_SCPositionData PositionData;
	sc.GetTradePosition(PositionData);

	if (PositionData.PositionQuantity == 0)
	{
		if (sc.Index > 0 && sc.BaseDateTimeIn[sc.Index].GetHour() != sc.BaseDateTimeIn[sc.Index - 1].GetHour())
		{
			if ((int)sc.BuyEntry(NewOrder) > 0)
			{
				entryBarIdx = sc.Index;
			}
		}
	}
	else if (entryBarIdx >= 0)
	{
		if (sc.Index >= entryBarIdx + holdBars_Input.GetInt())
		{
			if ((int)sc.BuyExit(NewOrder) > 0)
			{
				entryBarIdx = -1;
			}
		}
	}

}
