using NinjaTrader.Cbi;
using NinjaTrader.NinjaScript;
using System;
using System.Linq;
namespace NinjaTrader.NinjaScript.AddOns
{
public class OrderReplicatorAddOn : AddOnBase
{
private Account masterAccount; // Conta mestre
private Account followerAccount; // Conta seguidora
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Name = "OrderReplicatorAddOn";
Description = "Add-on para replicar ordens entre contas.";
}
else if (State == State.Configure)
{
// Configura as contas mestre e seguidora
masterAccount = Account.All.FirstOrDefault(a => a.Name == "MasterAccountName");
followerAccount = Account.All.FirstOrDefault(a => a.Name == "FollowerAccountName");
if (masterAccount == null || followerAccount == null)
{
Log("Conta mestre ou seguidora não encontrada!", LogLevel.Error);
return;
}
}
}
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
{
// Verifica se a execução é da conta mestre
if (execution.Account == masterAccount)
{
// Replica a execução na conta seguidora
switch (execution.Order.OrderState)
{
case OrderState.Filled:
ReplicateOrder(execution);
break;
case OrderState.Cancelled:
case OrderState.Rejected:
// Fecha a posição na conta seguidora se a ordem for cancelada ou rejeitada na conta mestre
followerAccount.Flatten(execution.Order.Instrument);
break;
}
}
}
private void ReplicateOrder(Execution execution)
{
// Obtém os detalhes da ordem
Instrument instrument = execution.Order.Instrument;
MarketPosition position = execution.Order.MarketPosition;
int quantity = execution.Order.Quantity;
// Replica a ordem na conta seguidora
if (position == MarketPosition.Long)
{
followerAccount.CreateMar****rder(instrument, position, quantity);
}
else if (position == MarketPosition.Short)
{
followerAccount.CreateMar****rder(instrument, position, quantity);
}
// Replica stop-loss e take-profit (se existirem)
if (execution.Order.StopLoss != null)
{
followerAccount.CreateStopMar****rder(instrument, position == MarketPosition.Long ? MarketPosition.Short : MarketPosition.Long, quantity, execution.Order.StopLoss.Price);
}
if (execution.Order.TakeProfit != null)
{
followerAccount.CreateLimitOrder(instrument, position == MarketPosition.Long ? MarketPosition.Short : MarketPosition.Long, quantity, execution.Order.TakeProfit.Price);
}
}
}
}

Comment