|
| 1 | +/* |
| 2 | + * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. |
| 3 | + * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | +*/ |
| 15 | + |
| 16 | +using System; |
| 17 | +using QuantConnect.Algorithm.Framework.Portfolio; |
| 18 | +using QuantConnect.Algorithm.Framework.Portfolio.SignalExports; |
| 19 | +using QuantConnect.Data; |
| 20 | +using QuantConnect.Indicators; |
| 21 | +using QuantConnect.Interfaces; |
| 22 | +using System.Collections.Generic; |
| 23 | +using Newtonsoft.Json; |
| 24 | +using System.Net.Http; |
| 25 | +using System.Text; |
| 26 | +using System.Net.Http.Json; |
| 27 | +using QuantConnect.Api; |
| 28 | +using QuantConnect.Util; |
| 29 | + |
| 30 | +namespace QuantConnect.Algorithm.CSharp |
| 31 | +{ |
| 32 | + /// <summary> |
| 33 | + /// This algorithm sends a list of portfolio targets to custom endpoint every time the ema indicators crosses between themselves |
| 34 | + /// </summary> |
| 35 | + /// <meta name="tag" content="using data" /> |
| 36 | + /// <meta name="tag" content="using quantconnect" /> |
| 37 | + /// <meta name="tag" content="securities and portfolio" /> |
| 38 | + public class CustomSignalExportDemonstrationAlgorithm : QCAlgorithm |
| 39 | + { |
| 40 | + private ExponentialMovingAverage _fast; |
| 41 | + private ExponentialMovingAverage _slow; |
| 42 | + private bool _emaFastWasAbove; |
| 43 | + private bool _emaFastIsNotSet; |
| 44 | + private bool _firstCall = true; |
| 45 | + |
| 46 | + private PortfolioTarget[] _targets = new PortfolioTarget[4]; |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Our custom signal export accepts all asset types |
| 50 | + /// </summary> |
| 51 | + private List<Symbol> _symbols = |
| 52 | + [ |
| 53 | + QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA, null, null), |
| 54 | + QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda, null, null), |
| 55 | + QuantConnect.Symbol.CreateFuture("ES", Market.CME, new DateTime(2023, 12, 15), null), |
| 56 | + QuantConnect.Symbol.CreateOption("GOOG", Market.USA, OptionStyle.American, OptionRight.Call, 130, new DateTime(2023, 9, 1)), |
| 57 | + ]; |
| 58 | + |
| 59 | + /// <summary> |
| 60 | + /// Initialize the date and add all equity symbols present in _symbols list. |
| 61 | + /// Besides, make a new PortfolioTarget for each symbol in _symbols, assign it |
| 62 | + /// an initial quantity and save it in _targets array |
| 63 | + /// </summary> |
| 64 | + public override void Initialize() |
| 65 | + { |
| 66 | + SetStartDate(2013, 10, 07); |
| 67 | + SetEndDate(2013, 10, 11); |
| 68 | + SetCash(100 * 1000); |
| 69 | + |
| 70 | + var index = 0; |
| 71 | + foreach (var item in _symbols) |
| 72 | + { |
| 73 | + var symbol = AddSecurity(item).Symbol; |
| 74 | + if (symbol.SecurityType == SecurityType.Equity |
| 75 | + || symbol.SecurityType == SecurityType.Forex) |
| 76 | + { |
| 77 | + _targets[index] = new PortfolioTarget(symbol, (decimal)0.05); |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + _targets[index] = new PortfolioTarget(symbol, 1); |
| 82 | + } |
| 83 | + index++; |
| 84 | + } |
| 85 | + |
| 86 | + _fast = EMA("SPY", 10); |
| 87 | + _slow = EMA("SPY", 100); |
| 88 | + |
| 89 | + // Initialize this flag, to check when the ema indicators crosses between themselves |
| 90 | + _emaFastIsNotSet = true; |
| 91 | + |
| 92 | + // Set CustomSignalExport signal export provider. |
| 93 | + SignalExport.AddSignalExportProviders(new CustomSignalExport()); |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Reduce the quantity of holdings for SPY or increase it, depending the case, |
| 98 | + /// when the EMA's indicators crosses between themselves, then send a signal to API |
| 99 | + /// </summary> |
| 100 | + /// <param name="slice"></param> |
| 101 | + public override void OnData(Slice slice) |
| 102 | + { |
| 103 | + if (IsWarmingUp) return; |
| 104 | + |
| 105 | + // Place an order as soon as possible to send a signal. |
| 106 | + if (_firstCall) |
| 107 | + { |
| 108 | + SetHoldings("SPY", 0.1); |
| 109 | + _targets[0] = new PortfolioTarget(Portfolio["SPY"].Symbol, (decimal)0.1); |
| 110 | + SignalExport.SetTargetPortfolio(_targets); |
| 111 | + _firstCall = false; |
| 112 | + } |
| 113 | + |
| 114 | + // Set the value of flag _emaFastWasAbove, to know when the ema indicators crosses between themselves |
| 115 | + if (_emaFastIsNotSet) |
| 116 | + { |
| 117 | + if (_fast > _slow * 1.001m) |
| 118 | + { |
| 119 | + _emaFastWasAbove = true; |
| 120 | + } |
| 121 | + else |
| 122 | + { |
| 123 | + _emaFastWasAbove = false; |
| 124 | + } |
| 125 | + _emaFastIsNotSet = false; |
| 126 | + } |
| 127 | + |
| 128 | + // Check whether ema fast and ema slow crosses. If they do, set holdings to SPY |
| 129 | + // or reduce its holdings, change its value in _targets array and send signals |
| 130 | + // to the API from _targets array |
| 131 | + if ((_fast > _slow * 1.001m) && (!_emaFastWasAbove)) |
| 132 | + { |
| 133 | + SetHoldings("SPY", 0.1); |
| 134 | + _targets[0] = new PortfolioTarget(Portfolio["SPY"].Symbol, (decimal)0.1); |
| 135 | + SignalExport.SetTargetPortfolio(_targets); |
| 136 | + } |
| 137 | + else if ((_fast < _slow * 0.999m) && (_emaFastWasAbove)) |
| 138 | + { |
| 139 | + SetHoldings("SPY", 0.01); |
| 140 | + _targets[0] = new PortfolioTarget(Portfolio["SPY"].Symbol, (decimal)0.01); |
| 141 | + SignalExport.SetTargetPortfolio(_targets); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + internal class CustomSignalExport : ISignalExportTarget |
| 147 | + { |
| 148 | + private readonly Uri _requestUri = new ("http://localhost:5000/"); |
| 149 | + private Lazy<HttpClient> _lazyClient = new(); |
| 150 | + protected HttpClient HttpClient => _lazyClient.Value; |
| 151 | + |
| 152 | + public bool Send(SignalExportTargetParameters parameters) |
| 153 | + { |
| 154 | + var message = JsonConvert.SerializeObject(parameters.Targets); |
| 155 | + using var httpMessage = new StringContent(message, Encoding.UTF8, "application/json"); |
| 156 | + using HttpResponseMessage response = HttpClient.PostAsync(_requestUri, httpMessage).Result; |
| 157 | + var result = response.Content.ReadFromJsonAsync<RestResponse>().Result; |
| 158 | + return result.Success; |
| 159 | + } |
| 160 | + |
| 161 | + public void Dispose() |
| 162 | + { |
| 163 | + if (_lazyClient.IsValueCreated) |
| 164 | + { |
| 165 | + _lazyClient.Value.DisposeSafely(); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +/* |
| 172 | +# $ flask --app app run |
| 173 | +
|
| 174 | +# app.py: |
| 175 | +from flask import Flask, request, jsonify |
| 176 | +from json import loads |
| 177 | +app = Flask(__name__) |
| 178 | +@app.post('/') |
| 179 | +def handle_positions(): |
| 180 | + result = loads(request.data) |
| 181 | + return jsonify({'success': True,'message': f'{len(result)} positions received'}) |
| 182 | +if __name__ == '__main__': |
| 183 | + app.run(debug=True) |
| 184 | +*/ |
0 commit comments