Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
I would like to open orders called DELTA LONG and DELTA SHO
Collapse
X
-
This is exactly what I didn't know, that is, I believed that having a LONG order open, you could also have a SHORT order open and instead from this answer you gave me, I'm understanding that it is not feasible; so in my case where when LONG is open, its Take Profit and Stop Loss appear on the chart, then SHORT opens with its Stop Loss and Take Profit, as soon as SHORT opens the Chart Trader goes into FLAT (so as it should be) and since on the chart (despite being in FLAT) the Stop Loss and Take Profit of the LONG also always remain active, in the code I have to specify that if there is a LONG open when a SHORT opens, the code must ensure that when the SHORT opens, the Stop Loss and Take Profit of the LONG are cancelled, right? Because as the code is written now, instead, they remain on the chart. Here, if I have to correct the code, then, do you already have some advice to give me? THANK YOU. CORDIALLY.
-
...and you have no idea how much you helped me because I didn't know where to turn anymore! THANK YOU.
Comment
-
Delta long 9.06 am , delta short 9.13 amAttached Files
Comment
-
Hello rottweiler,
Your code is using the unmanaged approach. No actions are automatic, any order management must be done by the script code.
If you are using another order to exit the long position, then you would need to cancel the stop and limit protecting the long position by supplying the orders to CancelOrder().
Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.
The 'ProfitChaseStopTrailUnmanagedExample' example from the link below demonstrates how to cancel orders using the unmanaged approach.
Chelsea B.NinjaTrader Customer Service
- Likes 1
Comment
-
Sorry if I insist; I did the counter test using the ATMs instead of the script of my automated strategy, as you can see from the screenshots NT8 makes me open multiple orders at the same time, in this example 3 LONG and 1 SHORT, 4 stop loss and 4 take profit remain, but on the Chart Trader 2 contracts; not knowing how the management of orders on NT8 works in general and specifically, using the code of my automated strategy the same thing happens as with the ATMs, but before doing the counter test with the ATMs, I thought it was an error in my script ... can you confirm that everything is regular? THANK YOU. CORDIALLY. I attach ATM screenshots and screenshots of the script in execution.
Comment
-
I understood and I manually tried "Display Selected ATM Strategy Only" by opening two Charts with the same financial instrument, THANK YOU; then I try it with my Ninjascript strategies, in one "add" a "long" strategy, in the other "add" a "short" strategy; I have already tested these two strategies in "PlayBack" and they work, they connect to the desired ATMStrategy; then in the ChartTrader I tried to select "Display Selected ATM Strategy Only" from the "Properties" when I activate my NinjaScript Strategies, but in this case (i.e. when my NinjaScript Strategies open orders), even if in the "Properties" I selected "Display Selected ATM Strategy Only", this property does not activate. I am looking in the "Help" section, also in the "script" documentation, but I can not find the way to make it so that when my Ninjascript strategy activates the ATMStrategy in "Display Selected ATM Strategy Only" mode. THANK YOU. CORDIALLY, so far you have solved all my problems and sorry if I am repetitive in writing, I am writing from Italy with the translator to try to explain myself as best as possible. THANK YOU SO MUCH. :#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
namespace NinjaTrader.NinjaScript.Strategies
{
public class DeltaLong : Strategy
{
region Variables
private double currentPtPrice, currentSlPrice, tickSizeSecondary;
private Order entryOrder, exitFlat, exitSession;
private Order placeHolderOrder, profitTarget, stopLoss;
private bool exitOnCloseWait, ordersCancelled, suppressCancelExit;
private string entryName, exitName, ptName, slName, message, ocoString;
private SessionIterator sessionIterator;
private OrderFlowCumulativeDelta cumulativeDelta;
private Dictionary<string, Order> activeOrders = new Dictionary<string, Order>();
private int currentBarIndex = -1;
private bool deltaLongOpenedThisBar = false;
private string atmStrategyId;
#endregion
region Properties
[NinjaScriptProperty]
[Display(Name = "Chase profit target", Order = 2, GroupName = "NinjaScriptStrategyParameters")]
public bool ChaseProfitTarget { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Profit target distance", Description = "Distance for profit target (in ticks)", Order = 3, GroupName = "NinjaScriptStrategyParameters")]
public int ProfitTargetDistance { get; set; }
[NinjaScriptProperty]
[Display(Name = "Print details", Order = 7, GroupName = "NinjaScriptStrategyParameters")]
public bool PrintDetails { get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name = "Stop loss distance", Description = "Distance for stop loss (in ticks)", Order = 6, GroupName = "NinjaScriptStrategyParameters")]
public int StopLossDistance { get; set; }
[NinjaScriptProperty]
[Display(Name = "Trail stop loss", Order = 5, GroupName = "NinjaScriptStrategyParameters")]
public bool TrailStopLoss { get; set; }
[NinjaScriptProperty]
[Display(Name = "Use profit target", Order = 1, GroupName = "NinjaScriptStrategyParameters")]
public bool UseProfitTarget { get; set; }
[NinjaScriptProperty]
[Display(Name = "Use stop loss", Order = 4, GroupName = "NinjaScriptStrategyParameters")]
public bool UseStopLoss { get; set; }
[NinjaScriptProperty]
public int MinTickMove { get; set; } = 4;
#endregion
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "Strategia Delta Long con gestione diretta degli ordini";
Name = "DeltaLong";
EntriesPerDirection = 100;
EntryHandling = EntryHandling.AllEntries;
ExitOnSessionCloseSeconds = 30;
IsExitOnSessionCloseStrategy = true;
IsUnmanaged = false; // Impostato su false per utilizzare l'ATM Strategy
TraceOrders = true;
IsInstantiatedOnEachOptimizationIteration = false;
ChaseProfitTarget = true;
PrintDetails = false;
ProfitTargetDistance = 10;
StopLossDistance = 10;
TrailStopLoss = true;
UseProfitTarget = true;
UseStopLoss = true;
}
else if (State == State.Configure)
{
AddDataSeries(Data.BarsPeriodType.Tick, 1);
}
else if (State == State.DataLoaded)
{
cumulativeDelta = OrderFlowCumulativeDelta(CumulativeDeltaType.BidAs k, CumulativeDeltaPeriod.Bar, 0);
}
else if (State == State.Historical)
{
sessionIterator = new SessionIterator(Bars);
tickSizeSecondary = BarsArray[1].Instrument.MasterInstrument.TickSize;
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress == 1)
{
cumulativeDelta.Update(cumulativeDelta.BarsArray[1].Count - 1, 1);
return;
}
if (currentBarIndex != CurrentBar)
{
deltaLongOpenedThisBar = false;
currentBarIndex = CurrentBar;
Print($"Nuova barra: {Time[0]}");
}
if (State != State.Realtime || CurrentBar < BarsRequiredToTrade || cumulativeDelta?.DeltaClose == null)
return;
double barRange = Math.Abs(Close[0] - Open[0]);
Print($"Bar {CurrentBar}: Close[0]={Close[0]}, Open[0]={Open[0]}, DeltaClose={cumulativeDelta.DeltaClose[0]}, DeltaOpen={cumulativeDelta.DeltaOpen[0]}, BarRange={barRange}");
// --- Condizioni Delta Long ---
if (activeOrders.Count < EntriesPerDirection)
{
if (!deltaLongOpenedThisBar && Close[0] > Open[0] && cumulativeDelta.DeltaClose[0] < cumulativeDelta.DeltaOpen[0] && (Close[0] - Open[0]) >= MinTickMove * TickSize)
{
ExecuteTrade("DELTA_LONG", OrderAction.Buy);
deltaLongOpenedThisBar = true;
}
}
}
private void ExecuteTrade(string signalName, OrderAction action)
{
string uniqueSignalName = $"{signalName}_{DateTime.Now:yyyyMMddHHmmssfff} ";
string uniqueOcoId = Guid.NewGuid().ToString();
Print($"Invio ordine: {uniqueSignalName}, Azione: {action}");
// Utilizza l'ATM Strategy "2 CONTRATTI"
AtmStrategyCreate(
action == OrderAction.Buy ? Cbi.OrderAction.Buy : Cbi.OrderAction.SellShort, // Azione (Buy o SellShort)
OrderType.Market, // Tipo di ordine
0, // Prezzo di ingresso (0 per Market Order)
0, // Stop loss (gestito dall'ATM Strategy)
0, // Take profit (gestito dall'ATM Strategy)
uniqueOcoId, // Durata dell'ordine come stringa unica
"2 CONTRATTI", // Nome dell'ATM Strategy
uniqueSignalName, // Nome univoco per l'ordine
(errorCode, strategyId) => // Callback con due parametri
{
if (errorCode != ErrorCode.NoError)
{
Print($"Errore nella creazione dell'ATM Strategy: {errorCode}");
}
else
{
Print($"ATM Strategy creata con successo per {uniqueSignalName}");
atmStrategyId = strategyId;
}
});
// Reset atmStrategyId to null immediately after creating the order
atmStrategyId = null;
}
protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
{
if (execution.Order.OrderState != OrderState.Filled)
return;
Print($"Ordine eseguito: {execution.Order.Name} a {price}");
if (activeOrders.ContainsKey(execution.Order.Name))
{
activeOrders.Remove(execution.Order.Name);
}
}
protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string comment)
{
Print(order.ToString());
if (order.OrderState == OrderState.Rejected)
{
Print($"⚠️ Ordine {order.Name} RIFIUTATO: {order}");
if (activeOrders.ContainsKey(order.Name))
{
activeOrders.Remove(order.Name);
}
}
}
}
}
Comment
-
Hello rottweiler,
Atm strategy properties do not apply to NinjaScript Strategies.
An account has one position per instrument. If you are showing 'Display Selected ATM Strategy Only' this shows the position of an atm in relation to that Atm but does not reflect the actual account position.
A NinjaScript Strategy has only one position per instrument, just like the account only has one position per instrument.
Atm strategy methods are like manual orders that do not affect the strategy position and not update order methods like OnOrderUpdate(), OnExecutionUpdate(), or OnPositionUpdate().
Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.
When using Atm Strategy methods, Chart Trader will reflect the selected active atm and atm strategy selection mode.
The strategy does not see any of that.
You would need to select the active atm strategy from the Atm Strategy drop-down in Chart Trader once this is active.Chelsea B.NinjaTrader Customer Service
Comment
-
Ok, so to have a LONG and a SHORT position open at the same time on the same financial instrument, I should open a chart (example ES with LONG position) with one account and another chart (example ES with SHORT position) with another account different from the one of the chart with the LONG position, right? Did I understand correctly? THANK YOU. KINDLY REGARDS.
Comment
-
Hello rottweiler,
"Ok, so to have a LONG and a SHORT position open at the same time on the same financial instrument"
You cannot have a long and short position on the same instrument on the same account. There is only one position for each instrument on an account.
You may be able to open separate accounts with your brokerage and have opposite positions on the same instrument on different accounts, if your brokerage allows that. This is known as hedging which is not allowed in the United States and is not allowed with NinjaTrader Brokerage.
That said, with Atms, you can view the PnL and relative position of an Atm. This is not an actual position but rather intended to show the profitability of a specific atm instance.Chelsea B.NinjaTrader Customer Service
Comment
-
I have to say that your contribution is really precious, THANK YOU, going forward you are enlightening me more and more. Do you happen to know which Brokers allow it? Thinking about it as I am writing, I could have the account with Ninja Trader Brokerage and another account with a different Broker (I am in Italy); however, are you aware of which Brokers allow separate accounts? For example Rithmic? THANK YOU. CORDIALLY.
Comment
-
Perfect, THANK YOU, you have already done a lot for me. THANK YOU AND GOOD WORK AND CONGRATULATIONS FOR YOUR PROFESSIONALISM.
Comment
-
Hi, I managed to put the trail stop in the script of my DELTA LONG strategy; the strategy opens an order with two contracts with a stop loss of 10 ticks and a take profit at 10 ticks and one at 14 ticks; the trail stop is activated after 10 ticks and is positioned 8 ticks below this price of 10 ticks reached (so two ticks above the entry price); what I noticed (I'll point out that I'm testing the strategy with playback, but I'm about to subscribe to the data feed to test it in demo) is that if the price reaches 10 ticks and the shadow is created, the trail stop is not activated (the stop loss is not positioned above the entry price); if instead the price reaches 10 ticks but the full candle body is created, the trail stop is activated and therefore is positioned above the entry price (as expected) ... so I don't understand what could be the reason for this difference ...
Another thing I noticed is that in any case the trail stop follows the price, as the price rises, the stop loss continues to rise always remaining below 8 ticks to the current price: what I would like to know is if there is a code to write in the script to ensure that it is activated only once when the price reaches 10 ticks for the first time and then just stays there, that it does not continue to follow the price; and then, please, I would like to know if there is also a code to write in the script that can manage the trail stop and that is, I mean, for example: the price reaches 10 ticks then the stop loss moves two ticks above the entry price and then maybe I want it to follow the current price every 2 ticks instead of one. THANK YOU. YOURS. Let me know if you want me to write the full code too.
Comment
-
Hello rottweiler,
If you are using SubmitOrderUnmanaged() you can set the stop price to any valid price (above the ask for a buy below the bid for a sell) and modify the price at any time as long as the order is still working.
To confirm, you have used the example I provided in post # 20 as a guide?
What logic do you have to modify the stop price only once?Chelsea B.NinjaTrader Customer Service
Comment
Latest Posts
Collapse
Topics | Statistics | Last Post | ||
---|---|---|---|---|
Started by Cameronpanek1, Today, 09:43 PM
|
0 responses
9 views
0 likes
|
Last Post
![]() |
||
Started by roykesler16, Today, 09:12 PM
|
0 responses
4 views
0 likes
|
Last Post
![]()
by roykesler16
Today, 09:12 PM
|
||
Started by iantriestrading, 04-19-2025, 10:23 AM
|
3 responses
56 views
0 likes
|
Last Post
![]() |
||
Started by raysinred, Yesterday, 02:05 PM
|
2 responses
20 views
0 likes
|
Last Post
![]()
by raysinred
Today, 06:48 PM
|
||
Started by fredfred123, 09-29-2017, 05:16 AM
|
5 responses
809 views
0 likes
|
Last Post
![]() |
Comment