Skip to content

Commit

Permalink
Ensure all trades close at the end of the run
Browse files Browse the repository at this point in the history
  • Loading branch information
mccaffers committed Feb 4, 2024
1 parent 346dc32 commit aa2dd0d
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 13 deletions.
2 changes: 1 addition & 1 deletion scripts/backtestings/aws.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ main() {

######################################
### EXPERIMENT DEFINITION
source $my_dir/experiments/momentum/indices/fixed
source $my_dir/experiments/momentum/forex/momentum_14a2da93_focused
######################################

# Remove binary files & tests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/bash
declare -a strategies=("Momentum_4d991e3b")
# declare -a symbolsArray=("EURUSD" "USDJPY" "GBPUSD" "NZDUSD" "USDCHF" "USDCAD" "AUDUSD")
declare -a symbolsArray=("GBPUSD" "NZDUSD" "USDCAD" "AUDUSD")

# Forex from 2004
yearsStart=2004
yearsEnd=2023

# These don't mean anything in RandomHHLL as the SL/TP is defined by the highest and lowest value from the last time period
stopLossInPipsRange="200 1 200" # STOP LOSS Distance in PIPs
limitInPipsRange="200 1 200" # TAKE PROFIT Distance in PIPs

# Account Equity
accountEquity=10000
maximumDrawndownPercentage=75
fasterProcessingBySkippingSomeTickData=true

# Strategy Variables
randomStrategyAmountOfHHLLSseq="5 5 15"
1 change: 1 addition & 0 deletions src/Interfaces/ICloseOrder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace backtesting_engine.interfaces;

public interface ICloseOrder
{
void Request(RequestObject reqObj, PriceObj priceObj, bool completed);
void Request(RequestObject reqObj, PriceObj priceObj);
void PushRequest(PriceObj priceObj);
}
4 changes: 2 additions & 2 deletions src/backtesting/Analysis/Reporting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ public void EndOfRunReport(string reason = "")
elasticClient.Index(report, b => b.Index("report"));

// Give the requests enough time to clean up, probably
// not necessary with the above await operators
System.Threading.Thread.Sleep(3000);
// not super necessary with the above await operators
Thread.Sleep(4000);
}

public virtual async Task SendStack(TradingException message)
Expand Down
14 changes: 7 additions & 7 deletions src/backtesting/Operations/Positions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ namespace backtesting_engine_operations;

public interface IPositions
{
void CloseAll();
void CloseAll(bool completed);
IEnumerable<RequestObject> GetOrderBook(string symbol);
Task Review(PriceObj priceObj);
void TrailingStopLoss(PriceObj priceObj);
void UpdateTradeHistory(RequestObject reqObj, PriceObj priceObj);
void UpdateTradeHistory(RequestObject reqObj, PriceObj priceObj, bool completed);
void ReviewEquity();
void PushRequests(PriceObj priceObj);
}
}

public class Positions : TradingBase, IPositions
{
Expand Down Expand Up @@ -107,11 +107,11 @@ public void ReviewEquity()
}
}

public void CloseAll()
public void CloseAll(bool completed = false)
{
foreach (var item in this.tradingObjects.openTrades)
{
UpdateTradeHistory(item.Value, item.Value.priceObj);
UpdateTradeHistory(item.Value, item.Value.priceObj, completed);
}
}

Expand Down Expand Up @@ -151,9 +151,9 @@ public IEnumerable<RequestObject> GetOrderBook(string symbol)
}
}

public void UpdateTradeHistory(RequestObject reqObj, PriceObj priceObj)
public void UpdateTradeHistory(RequestObject reqObj, PriceObj priceObj, bool completed = false)
{
closeOrder.Request(reqObj, priceObj);
closeOrder.Request(reqObj, priceObj, completed);
}


Expand Down
12 changes: 11 additions & 1 deletion src/backtesting/SystemSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Net;
using backtesting_engine.analysis;
using backtesting_engine.interfaces;
using backtesting_engine_operations;
using Microsoft.Extensions.DependencyInjection;
using Nest;
using trading_exception;
Expand All @@ -15,13 +16,19 @@ public class SystemSetup : ISystemSetup
readonly IReporting elastic;
readonly IElasticClient es;
readonly IServiceProvider provider;
readonly IPositions positions;

public SystemSetup(IServiceProvider provider, IReporting elastic, IElasticClient es, IEnvironmentVariables envVariables)
public SystemSetup(IServiceProvider provider,
IReporting elastic,
IElasticClient es,
IEnvironmentVariables envVariables,
IPositions positions)
{
this.envVariables = envVariables;
this.elastic = elastic;
this.provider = provider;
this.es = es;
this.positions = positions;

Task<string>.Run(async () =>
{
Expand All @@ -47,6 +54,9 @@ public SystemSetup(IServiceProvider provider, IReporting elastic, IElasticClient
}).ContinueWith(taskOutput =>
{
ConsoleLogger.Log(taskOutput.Result);
ConsoleLogger.Log("End of trading run - closing down any open trades");
positions.CloseAll(true);
Thread.Sleep(500);
elastic.EndOfRunReport(taskOutput.Result);
}).Wait();
}
Expand Down
16 changes: 14 additions & 2 deletions src/backtesting/TradeManagement/CloseOrder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,17 @@ public class CloseOrder : TradingBase, ICloseOrder
}
}

// Data Update
public void Request(RequestObject reqObj, PriceObj priceObj)
{
RequestHandler(reqObj, priceObj, false);
}

public void Request(RequestObject reqObj, PriceObj priceObj, bool completed)
{
RequestHandler(reqObj, priceObj, completed);
}
// Data Update
private void RequestHandler(RequestObject reqObj, PriceObj priceObj, bool completed)
{

TradeHistoryObject tradeHistoryObj = new TradeHistoryObject();
Expand All @@ -49,7 +58,10 @@ public void Request(RequestObject reqObj, PriceObj priceObj)

PropertyCopier<RequestObject, TradeHistoryObject>.Copy(reqObj, tradeHistoryObj);

if(!cache.ContainsKey(tradeHistoryObj.key)){
if(completed) {
// Immediately close the trade if we are at the end
CloseTrade(tradeHistoryObj);
} else if(!cache.ContainsKey(tradeHistoryObj.key)){
cache.Add(tradeHistoryObj.key, tradeHistoryObj);
}
}
Expand Down
File renamed without changes.
File renamed without changes.

0 comments on commit aa2dd0d

Please sign in to comment.