Skip to content

Commit

Permalink
Seperated out the experiements to record their setup, updated the web…
Browse files Browse the repository at this point in the history
… ui to prevent CORS issues, and started on a new momentum calculator
  • Loading branch information
mccaffers committed Jan 19, 2024
1 parent 74d4bdf commit d5f5743
Show file tree
Hide file tree
Showing 12 changed files with 179 additions and 13 deletions.
3 changes: 2 additions & 1 deletion scripts/backtestings/aws.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ main() {
# randomStrategyAmountOfHHLLSseq="5 5 5"

# source $my_dir/experiments/random/forex/fixed
source $my_dir/experiments/random/forex/variable
source $my_dir/experiments/random/crypto/variable
# source $my_dir/experiments/momentum/ftse100
######

# Remove binary files & tests
Expand Down
19 changes: 19 additions & 0 deletions scripts/backtestings/experiments/momentum/ftse100
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
declare -a strategies=("Momentum")

## Multiple Indexes
declare -a symbolsArray=("GBRIDXGBP")

# Forex from 2004
yearsStart=2014
yearsEnd=2023

# STOP LOSS Distance in PIPs
stopLossInPipsRange="100 100 1000"

# TAKE PROFIT Distance in PIPs
limitInPipsRange="100 100 1000"

# Account Equity
accountEquity=500
maximumDrawndownPercentage=50
fasterProcessingBySkippingSomeTickData=true
3 changes: 3 additions & 0 deletions scripts/backtestings/experiments/random/crypto/variable
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#!/bin/bash

declare -a strategies=("RandomStrategy")

## Crypto
declare -a symbolsArray=("ETHUSD" "BTCUSD")
yearsStart=2018
yearsEnd=2023

# STOP LOSS Distance in PIPs
stopLossInPipsRange="20 20 100"
Expand Down
1 change: 1 addition & 0 deletions scripts/backtestings/experiments/random/forex/fixed
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ declare -a symbolsArray=("EURUSD" "USDJPY" "GBPUSD" "NZDUSD" "USDCHF" "USDCAD" "

# Forex from 2004
yearsStart=2004
yearsEnd=2023

# STOP LOSS Distance in PIPs
stopLossInPipsRange="30 1 30"
Expand Down
1 change: 1 addition & 0 deletions scripts/backtestings/experiments/random/forex/trailingSL
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ declare -a symbolsArray=("EURUSD" "USDJPY" "GBPUSD" "NZDUSD" "USDCHF" "USDCAD" "

# Forex from 2004
yearsStart=2004
yearsEnd=2023

# STOP LOSS Distance in PIPs
stopLossInPipsRange="200 20 200"
Expand Down
4 changes: 4 additions & 0 deletions scripts/backtestings/experiments/random/forex/variable
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#!/bin/bash

declare -a strategies=("RandomStrategy")

## Multiple Currencies
declare -a symbolsArray=("EURUSD" "USDJPY" "GBPUSD" "NZDUSD" "USDCHF" "USDCAD" "AUDUSD")

# Forex from 2004
Expand Down
1 change: 1 addition & 0 deletions scripts/backtestings/experiments/random/indices/fixed
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ declare -a symbolsArray=("JPNIDXJPY" "ESPIDXEUR" "FRAIDXEUR" "DEUIDXEUR" "AUSIDX

# Forex from 2004
yearsStart=2014
yearsEnd=2023

# STOP LOSS Distance in PIPs
stopLossInPipsRange="30 1 30"
Expand Down
3 changes: 3 additions & 0 deletions scripts/backtestings/experiments/random/indices/variable
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
#!/bin/bash

declare -a strategies=("RandomStrategy")

## Multiple Indexes
declare -a symbolsArray=("JPNIDXJPY" "ESPIDXEUR" "FRAIDXEUR" "DEUIDXEUR" "AUSIDXAUD" "USATECHIDXUSD" "USA500IDXUSD" "USA30IDXUSD" "EUSIDXEUR" "GBRIDXGBP")

# Forex from 2004
yearsStart=2014
yearsEnd=2023

# STOP LOSS Distance in PIPs
stopLossInPipsRange="20 20 100"
Expand Down
2 changes: 1 addition & 1 deletion src/backtesting/Consumer/WebConsumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task ConsumeAsync(BufferBlock<PriceObj> buffer, CancellationToken c

private async Task CacheRequests(PriceObj priceObj){
// Clock the local time, check it's under 100 milliseconds
if(DateTime.Now.Subtract(lastReceived).TotalSeconds <= 0.2){ //0.4
if(DateTime.Now.Subtract(lastReceived).TotalSeconds <= 0.1){ //0.4

// Have we sent an hour
if(priceObj.date.Subtract(priceTimeWindow).TotalMinutes<5){
Expand Down
137 changes: 137 additions & 0 deletions src/strategies/Momentum.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using System.Diagnostics.CodeAnalysis;
using backtesting_engine;
using backtesting_engine.interfaces;
using backtesting_engine_models;
using Newtonsoft.Json;
using Utilities;

namespace backtesting_engine_strategies;

// https://mccaffers.com/randomly_trading/
public class Momentum : BaseStrategy, IStrategy
{

private List<OhlcObject> ohlcList = new List<OhlcObject>();
private OhlcObject lastItem = new OhlcObject();
private DateTime lastReportedEvent = DateTime.MinValue;
private PriceObj? earlyMorningPrice;
private PriceObj? lateMorningPrice;

public Momentum( IRequestOpenTrade requestOpenTrade,
ITradingObjects tradeObjs,
IEnvironmentVariables envVariables,
ICloseOrder closeOrder,
IWebNotification webNotification ) : base(requestOpenTrade, tradeObjs, envVariables, closeOrder, webNotification) {}


public async Task Invoke(PriceObj priceObj)
{

foreach(var item in this.tradeObjs.openTrades.Where(x => x.Key.Contains(priceObj.symbol)).Select(x => x.Value)){
if(priceObj.date.Subtract(item.openDate).TotalHours > 1 && item.profit > 10){
this.closeOrder.Request(item, priceObj);
return;
}

if(priceObj.date.Subtract(item.openDate).TotalHours > 3 && item.profit > 5){
this.closeOrder.Request(item, priceObj);
return;
}
if(priceObj.date.Subtract(item.openDate).TotalHours > 4 && item.profit > 0){
this.closeOrder.Request(item, priceObj);
return;
}
}
// Maximum of one open trade
// TODO Make configurable
if (tradeObjs.openTrades.Count() >= 1)
{
return;
}

if(lastReportedEvent == DateTime.MinValue){
lastReportedEvent = priceObj.date;
return;
}


var randomInt = new Random().Next(8);

// TradeDirection direction = TradeDirection.BUY;

if (randomInt==0)
{
return;
}

// if(priceObj.date.DayOfWeek == DayOfWeek.Sunday)
// {
// return;
// }

if(priceObj.date.Hour < 6 || priceObj.date.Hour > 23){
return;
}

if(priceObj.date.DayOfWeek == DayOfWeek.Sunday || priceObj.date.DayOfWeek == DayOfWeek.Friday ){
return;
}

// The day has changed
// if(lastReportedEvent.Hour != priceObj.date.Hour) {
// After 7 am, lets start recording
if(earlyMorningPrice == null){
earlyMorningPrice=priceObj;
}

// After 7 am, lets start recording
if(earlyMorningPrice?.date.Subtract(priceObj.date).TotalMinutes < -30 && lateMorningPrice == null) {
lateMorningPrice=priceObj;
}

if(earlyMorningPrice!=null && lateMorningPrice != null){
lastReportedEvent=priceObj.date.Date;
var diff = 1 - (earlyMorningPrice.bid / lateMorningPrice.bid);

if(Math.Abs(diff*1000) >= 1 ){

TradeDirection dir = TradeDirection.SELL;
if(diff > 0) {
dir = TradeDirection.BUY;
}
var size = decimal.Parse(envVariables.tradingSize);


OpenTrade(priceObj, dir, size);


}

earlyMorningPrice=null;
lateMorningPrice=null;
}

// }


// Surpress CS1998
// Async method lacks 'await' operators and will run synchronously
await Task.CompletedTask;

return;
}

private void OpenTrade(PriceObj priceObj, TradeDirection direction, decimal size){

var key = DictionaryKeyStrings.OpenTrade(priceObj.symbol, priceObj.date);

var openOrderRequest = new RequestObject(priceObj, direction, envVariables, key)
{
size = size ,
stopDistancePips = decimal.Parse(envVariables.stopDistanceInPips),
limitDistancePips = decimal.Parse(envVariables.limitDistanceInPips),
};

this.requestOpenTrade.Request(openOrderRequest);
}
}
2 changes: 1 addition & 1 deletion src/ui/src/TradingUI/Dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ const Chat = () => {

function connectToSignalR(){
const connection = new HubConnectionBuilder()
.withUrl('http:https://localhost:5000/hubs/chat', { transport: HttpTransportType.WebSockets | HttpTransportType.LongPolling })
.withUrl('http:https://localhost:5000/hubs/chat', {skipNegotiation:true, withCredentials:false, transport: HttpTransportType.WebSockets })
.withHubProtocol(new signalRMsgPack.MessagePackHubProtocol())
.withAutomaticReconnect()
.build();
Expand Down
16 changes: 6 additions & 10 deletions src/webserver/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,11 @@ public void ConfigureServices(IServiceCollection services)

services.AddCors(options =>
{
options.AddPolicy("ClientPermission", policy =>
{
policy.WithOrigins("http:https://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
});
options.AddPolicy("ClientPermission", pb =>
pb.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
);
});
}

Expand All @@ -43,7 +40,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


app.UseHttpsRedirection();



app.UseRouting();
Expand All @@ -52,7 +48,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/hubs/chat");
Expand Down

0 comments on commit d5f5743

Please sign in to comment.