Esta página fornece vários exemplos de código Python e C# para criar plugins nativos, incluindo ferramentas para negociação manual ou algorítmica no cTrader.
Repositórios de amostras de plugins
Amostras de código de plugins abrangentes, incluindo modelos prontos a executar para várias áreas e funcionalidades da interface do utilizador, estão disponíveis em repositórios separados Python e C# no GitHub.
Dica
Utilize parâmetros personalizáveis em plugins C# e Python para alcançar maior flexibilidade. Os parâmetros personalizáveis para plugins C# são declarados no código C# normal, enquanto os plugins Python requerem parâmetros personalizáveis declarados nos seus ficheiros .cs.
Apresentar um website num quadro de gráfico
O plugin seguinte apresenta o website da cTrader Store dentro de um quadro de gráfico separado.
Uma vez por minuto, o plugin abaixo guarda o lucro e perda (P&L) total da conta num ficheiro utilizando a funcionalidade de armazenamento local e o carimbo de data/hora atual como nome do ficheiro. Também apresenta a mesma informação numa secção separada no Painel de símbolo ativo (ASP).
importclrclr.AddReference("cAlgo.API")fromcAlgo.APIimport*classGrossPnL():defon_start(self):self.textBlock=TextBlock()self.textBlock.Text="Starting..."self.textBlock.FontSize=15self.textBlock.FontWeight=FontWeight.ExtraBoldself.textBlock.TextAlignment=TextAlignment.Centerself.textBlock.Padding=Thickness(5,5,5,5)aspBlock=api.Asp.SymbolTab.AddBlock("Gross P&L")aspBlock.Child=self.textBlockapi.Timer.Start(60)defon_timer(self):timestamp=api.Server.TimeInUtcresult=timestamp.ToString("HH mm ss")api.LocalStorage.SetString(result,f"{api.Account.UnrealizedGrossProfit}",LocalStorageScope.Device)self.textBlock.Text=f"{result}: {api.Account.UnrealizedGrossProfit}"
Apresentar uma janela separada com um controlo personalizado
O plugin abaixo adiciona um botão personalizado a uma janela separada. Ao clicar, o controlo adiciona um nível de take profit para todas as posições abertas, mas apenas se uma posição não tiver um take profit previamente estabelecido.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingcAlgo.API;usingcAlgo.API.Collections;usingcAlgo.API.Indicators;usingcAlgo.API.Internals;namespacecAlgo.Plugins{[Plugin(AccessRights = AccessRights.None)]publicclassProtectionPlugin:Plugin{privateButton_buttonAddTakeProfit;privateWindow_window;protectedoverridevoidOnStart(){_buttonAddTakeProfit=newButton{BackgroundColor=Color.SeaGreen,Height=50,Text="Add Take Profit"};_buttonAddTakeProfit.Click+=AddTakeProfit;_window=newWindow{Height=150,Width=150,Padding=newThickness(5,10,10,5),};_window.Child=_buttonAddTakeProfit;_window.Show();}privatevoidAddTakeProfit(ButtonClickEventArgsargs){foreach(varpositioninPositions){if(position.TakeProfitisnull){position.ModifyTakeProfitPips(20);}}}}}
importclrclr.AddReference("cAlgo.API")fromcAlgo.APIimport*classProtectionPlugin():defon_start(self):self.buttonAddTakeProfit=Button()self.buttonAddTakeProfit.BackgroundColor=Color.SeaGreenself.buttonAddTakeProfit.Height=50self.buttonAddTakeProfit.Text="Add Take Profit"self.buttonAddTakeProfit.Click+=self.On_add_take_profit_clickself.window=Window()self.window.Height=150self.window.Width=150self.window.Padding=Thickness(5,10,10,5)self.window.Child=self.buttonAddTakeProfitself.window.Show()defOn_add_take_profit_click(self,args):forpositioninapi.Positions:ifposition.TakeProfitisNone:position.ModifyTakeProfitPips(20)
Apresentar informações sobre preços de barras na visualização da Observação da Negociação
Quando construído, este plugin adiciona um novo separador ao painel Observação da Negociação. Este separador contém uma grelha de dois por dois que apresenta informações sobre os últimos preços de barras conhecidos para o intervalo de tempo m1 e o símbolo "USDJPY".
O plugin seguinte deteta qual ChartFrame está atualmente ativo. Dentro de um bloco personalizado no ASP, o plugin mostra a diferença percentual entre o preço atual do símbolo para o qual este ChartFrame está aberto e o preço deste símbolo há aproximadamente um mês atrás.
usingSystem;usingcAlgo.API;usingcAlgo.API.Collections;usingcAlgo.API.Indicators;usingcAlgo.API.Internals;namespacecAlgo.Plugins{[Plugin(AccessRights = AccessRights.None)]publicclassActiveFrameChangedSample:Plugin{// Declaring the necessary UI elementsprivateGrid_grid;privateTextBlock_percentageTextBlock;privateFrame_activeFrame;protectedoverridevoidOnStart(){// Initialising the grid and the TextBlock// displaying the percentage difference_grid=newGrid(1,1);_percentageTextBlock=newTextBlock{HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center,Text="Monthly change: ",};_grid.AddChild(_percentageTextBlock,0,0);// Initialising a new block inside the ASP// and adding the grid as a childvarblock=Asp.SymbolTab.AddBlock("Monthly Change Plugin");block.Child=_grid;// Attaching a custom handler to the// ActiveFrameChanged eventChartManager.ActiveFrameChanged+=ChartManager_ActiveFrameChanged;}privatevoidChartManager_ActiveFrameChanged(ActiveFrameChangedEventArgsobj){if(obj.NewFrameisChartFrame){// Casting the Frame into a ChartFramevarnewChartFrame=obj.NewFrameasChartFrame;// Attaining market data for the symbol for which// the currently active ChartFrame is openedvardailySeries=MarketData.GetBars(TimeFrame.Daily,newChartFrame.Symbol.Name);// Calculating the monthly change and displaying it// inside the TextBlockdoublemonthlyChange=(newChartFrame.Symbol.Bid-dailySeries.ClosePrices[dailySeries.ClosePrices.Count-30])/100;_percentageTextBlock.Text=$"Monthly change: {monthlyChange}";}}}}
importclrclr.AddReference("cAlgo.API")fromcAlgo.APIimport*classActiveFrameChangedSample():defon_start(self):# Initialising the grid and the TextBlock displaying the percentage differencegrid=Grid(1,1)self.percentageTextBlock=TextBlock()self.percentageTextBlock.HorizontalAlignment=HorizontalAlignment.Centerself.percentageTextBlock.VerticalAlignment=VerticalAlignment.Centerself.percentageTextBlock.Text="Monthly change: "grid.AddChild(self.percentageTextBlock,0,0)# Initialising a new block inside the ASP and adding the grid as a childblock=api.Asp.SymbolTab.AddBlock("Monthly Change Plugin")block.Child=grid# Attaching an event handler to the ActiveFrameChanged eventapi.ChartManager.ActiveFrameChanged+=self.on_chart_manager_active_frame_changeddefon_chart_manager_active_frame_changed(self,args):ifargs.NewFrameisNoneorisinstance(args.NewFrame.__implementation__,ChartFrame)==False:returnnewChartFrame=ChartFrame(args.NewFrame)# Attaining market data for the symbol for which the currently active ChartFrame is openeddailySeries=api.MarketData.GetBars(TimeFrame.Daily,newChartFrame.Symbol.Name)# Calculating the monthly change and displaying it inside the TextBlockmonthlyChange=(newChartFrame.Symbol.Bid-dailySeries.ClosePrices[dailySeries.ClosePrices.Count-30])/100self.percentageTextBlock.Text=f"Monthly change: {monthlyChange}"