Overnight Positioning with EMA Strategy
Enters a long position shortly before the selected market closes and exits after the market opens. An optional EMA filter confirms entries. The strategy supports US, Asian, and European sessions and closes any open position before the weekend.
Details
- Entry: Minutes before market close when price is above EMA (if enabled).
- Exit: After market open for the specified minutes or five minutes before Friday close.
- Market: US, Asia, or Europe.
- Indicator: EMA.
- Direction: Long only.
- Stops: None.
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
public class OvernightPositioningEmaStrategy : Strategy
{
private readonly StrategyParam<int> _emaLen;
private readonly StrategyParam<DataType> _candle;
private DateTime _currentDay;
private bool _tradeTakenToday;
public int EmaLength { get => _emaLen.Value; set => _emaLen.Value = value; }
public DataType CandleType { get => _candle.Value; set => _candle.Value = value; }
public OvernightPositioningEmaStrategy()
{
_emaLen = Param(nameof(EmaLength), 100).SetGreaterThanZero();
_candle = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_currentDay = default;
_tradeTakenToday = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_currentDay = default;
_tradeTakenToday = false;
var ema = new ExponentialMovingAverage { Length = EmaLength };
var sub = SubscribeCandles(CandleType);
sub.Bind(ema, (candle, emaVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!ema.IsFormed)
return;
var day = candle.OpenTime.Date;
if (_currentDay != day)
{
_currentDay = day;
_tradeTakenToday = false;
}
if (_tradeTakenToday)
return;
var hour = candle.OpenTime.Hour;
// Buy near end of day if above EMA
if (hour >= 15 && hour < 16 && candle.ClosePrice > emaVal && Position <= 0)
{
BuyMarket();
_tradeTakenToday = true;
}
// Sell near start of day
else if (hour >= 9 && hour < 10 && Position > 0)
{
SellMarket();
_tradeTakenToday = true;
}
}).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, sub);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class overnight_positioning_ema_strategy(Strategy):
def __init__(self):
super(overnight_positioning_ema_strategy, self).__init__()
self._ema_length = self.Param("EmaLength", 100) \
.SetGreaterThanZero()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._current_day = None
self._trade_taken_today = False
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(overnight_positioning_ema_strategy, self).OnReseted()
self._current_day = None
self._trade_taken_today = False
def OnStarted2(self, time):
super(overnight_positioning_ema_strategy, self).OnStarted2(time)
self._current_day = None
self._trade_taken_today = False
self._ema = ExponentialMovingAverage()
self._ema.Length = self._ema_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._ema, self.OnProcess).Start()
def OnProcess(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
if not self._ema.IsFormed:
return
ev = float(ema_val)
close = float(candle.ClosePrice)
day = candle.OpenTime.Date
if self._current_day is None or self._current_day != day:
self._current_day = day
self._trade_taken_today = False
if self._trade_taken_today:
return
hour = candle.OpenTime.Hour
if hour >= 15 and hour < 16 and close > ev and self.Position <= 0:
self.BuyMarket()
self._trade_taken_today = True
elif hour >= 9 and hour < 10 and self.Position > 0:
self.SellMarket()
self._trade_taken_today = True
def CreateClone(self):
return overnight_positioning_ema_strategy()