Skip to content

Commit

Permalink
Initial solution
Browse files Browse the repository at this point in the history
  • Loading branch information
JosueNina committed Jan 24, 2025
1 parent cad5f20 commit 93ab38f
Show file tree
Hide file tree
Showing 2 changed files with 127 additions and 0 deletions.
117 changes: 117 additions & 0 deletions Algorithm.CSharp/UpdateStopOrdersRegressionAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;

namespace QuantConnect.Algorithm.CSharp
{
public class UpdateStopOrdersRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private OrderTicket _ticket;

public override void Initialize()
{
// Inicializar las fechas y el capital inicial
SetStartDate(2018, 4, 3);

// Agregar el par de divisas EURUSD
AddForex("EURUSD", Resolution.Minute);
}

public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
var qty = CalculateOrderQuantity("EURUSD", 50m);

var ticketTest = MarketOrder("EURUSD", qty);

_ticket = StopMarketOrder("EURUSD", -qty / 2, Securities["EURUSD"].Price - 0.003m);

Log($"Before TotalMarginUsed: {Portfolio.TotalMarginUsed}");

var updateSettings = new UpdateOrderFields
{
Quantity = -qty * 10,
StopPrice = Securities["EURUSD"].Price - 0.003m
};
var response = _ticket.Update(updateSettings);

if (response.IsSuccess)
{
Log($"After TotalMarginUsed: {Portfolio.TotalMarginUsed}");
}
}
}

public override void OnOrderEvent(OrderEvent orderEvent)
{
var order = Transactions.GetOrderById(orderEvent.OrderId);
if (order.Type == OrderType.StopMarket && orderEvent.Status == OrderStatus.Filled)
{
_ticket = null;
}
}
/// <summary>
/// Final status of the algorithm
/// </summary>
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;

/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;

/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public virtual List<Language> Languages { get; } = new() { Language.CSharp };

/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 4543;

/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "10"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-0.468%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Start Equity", "100000"},
{"End Equity", "99985"},
{"Net Profit", "-0.015%"},
{"Sharpe Ratio", "-15.229"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0.781%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.003"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "-5.216"},
{"Tracking Error", "0.103"},
{"Treynor Ratio", "5.946"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$8000.00"},
{"Lowest Capacity Asset", "SPXW XKX6S2GM9PGU|SPX 31"},
{"Portfolio Turnover", "0.01%"},
{"OrderListHash", "5b50a3d9e0afad859c3f7e2580a4f3be"}
};
}
}
10 changes: 10 additions & 0 deletions Engine/TransactionHandlers/BrokerageTransactionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,16 @@ private OrderResponse HandleUpdateOrderRequest(UpdateOrderRequest request)

ticket.SetOrder(order);

var hasSufficientBuyingPowerResult = _algorithm.Portfolio.HasSufficientBuyingPowerForOrder([order]);

if (!hasSufficientBuyingPowerResult.IsSufficient)
{
var errorMessage = $@"Order Error: id: [{order.Id}], Insufficient buying power to complete order, Reason: {hasSufficientBuyingPowerResult.Reason}.";
_algorithm.Error(errorMessage);
InvalidateOrders([order], errorMessage);
return OrderResponse.Error(request, OrderResponseErrorCode.InsufficientBuyingPower, errorMessage);
}

bool orderUpdated;
if (isClosedOrderUpdate)
{
Expand Down

0 comments on commit 93ab38f

Please sign in to comment.