Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Integrating Amibroker with Python COM Server

2 min read

Why Python?

Building complex trading systems requires advanced mathematical models, which can be challenging to design using Amibroker alone. However, with the help of Python, it is possible to build intricate mathematical models more efficiently. Python is an open-source language, similar to C and C++, with a wealth of third-party modules available for financial computing and statistical modeling. These modules, such as numPy, sciPy, and pandas, can be utilized to develop complex models with ease. To learn more about these statistical packages, a quick search online will provide further information.

So if we can Integrate Amibroker with Python then probably it is like creating a gateway towards accessing complex mathematical models in Amibroker

New Method to Integrate Python with Amibroker: Access Python Functions using Amibroker – AmiPy Plugin (Works only with 64bit Amibroker 6.3 or higher version)

What is Python COM Server?

A Python COM Server refers to a component that uses the Component Object Model (COM) technology, which is a Microsoft framework for software componentry introduced in 1993. COM allows for the creation of reusable software components that can communicate with each other, particularly across different programming languages and processes.

Python COM servers are commonly used for automation tasks, where a Python script can provide automation services to other applications, like Microsoft Office products. For example, a Python COM server could be used to automate complex Excel tasks.

Python Com Server

A Python COM server needs to be registered in the Windows registry so that clients can discover and use it. Tools in Python libraries for COM integration usually provide easy ways to handle this registration

Installing Python

Install Python 3.x Version in your Windows Machine with VS Code Editor

Integrating Amibroker with Python COM Sever

Here I am going to demonstrate the AFL code by Bruce Peterson on Integrating Amibroker with Python using the IIR Filter example. IIR stands for Infinite impulse response (IIR) is a property applying to many linear time-invariant systems most commonly used in digital and electronic filters.

Steps to Follow

1)Copy iir.py Python Code and store it locally

# iir.py python file

import pythoncom
from win32com.server.exception import COMException
import win32com.server.util
import win32com.client.dynamic
import win32gui
import random


class PythonUtilities(object):
    _public_methods_=['IIR2']

    #
    # Use pythoncom.CreateGuid() 2/1/08
    #               
    _reg_clsid_="{25F32489-9E84-4D9F-8AEB-44DC9B528405}"
    _reg_desc_ =   "Utilities for Extending Amibroker AFL"
    _reg_progid_ = "PyAFL"
    _readonly_attrs_ = ['revision']

   # class attributes can be defined and used to transfer values from AFL

    _public_attrs_=['NDepVar','ArrayLen','ProbArray',
                    'X_Open','X_High','X_Low','X_Close',
                    'X_Volume','X_OI','Log']

    Log=""  # Log may be a  string use to pass text to AFL
    
    def IIR2(self,InList,coef0,coef1,coef2):
        # example infinite impulse response filter from Amibroker docs
        #
        self.revision="version 1"
        OutList=[]
##
##        print type(InList),type(coef0)
##        print coef0,coef1,coef2
##        
        InList=list(InList)
        
        if len(InList)==0:
            return OutList
        OutList=InList[0:2]
        for index in range(2,len(InList)):    
            OutList.append(coef0*InList[index]+coef1*InList[index-1]+coef2*InList[index-2])
        OutList.append(0)
        if OutList is None:
            return
        else:
            return OutList
 
    
        
if __name__=='__main__':
    print("Registering COM Server ")
    import win32com.server.register
    win32com.server.register.UseCommandLine(PythonUtilities)

# uncomment out if you want to unregister com server 

##    from win32com.server.register import UnregisterServer
##    UnregisterServer(PythonUtilities._reg_clsid_)
##    print "Com server unregistered."    

#############################################End Python Code
####################################

2)And execute the file with the command python iir.py as shown below



3)Copy the Python AFL.afl file and paste the file in \\Amibroker\\Formulas\\Basic Charts Folder

//Python AFL.afl
_SECTION_BEGIN("Candles");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();


_SECTION_BEGIN("IIR");
MyObj=CreateObject("PyAFL");  // link to python com server

Coef0=Param("Coef0",0.2,-5,5);
Coef1=Param("Ceof1",1.2,-5,5);
Coef2=Param("Coef2",-0.4,-5);

// COM object interface cannot deal with null value, set to zero to be sure

Close=Nz(Close);

 // use IIR2 method in com server to calculate smoothed value

SmValue = MyObj.IIR2(Close,Coef0,Coef1,Coef2);


Plot(C,"Close",Color=colorBlue,style=styleLine);
Plot(SmValue,"IIR2 smooth",colorGreen,styleLine|styleThick);

_SECTION_END();


_SECTION_BEGIN("DEMA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( DEMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ),
ParamStyle("Style") ); 
_SECTION_END();


4)Open a New Blank Chart and apply Python AFL.afl to it. You should be able to see IIR(Infinite Impulse Response) and DEMA lines over the Candlesticks where the IIR is computed with the help of Python COM as shown below

Nifty IIR2
Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

[Webinar] Understanding and Mitigating Curve Fitting in System Trading

"Understanding and Mitigating Curve Fitting in System Trading"! This dynamic session aims to equip novice to intermediate traders, quantitative analysts, and financial engineers with...
Rajandran R
1 min read

P-Signal Strategy Long Only Strategy – Amibroker AFL Code

This tutorial provides an overview of the P-Signal reversal strategy, a quantitative trading strategy that utilizes statistical parameters and error functions to generate probabilistic...
Rajandran R
2 min read

28 Replies to “Integrating Amibroker with Python COM Server”

  1. Hi rajendran sir .I am u r big fan. Watching u r live chart for 1 year learnt lot from it. your free live site is not working today 10-04-2014.kindly resolve them sir…

  2. Hi, thanks for the post.

    I am only able to return string or number back to amibroker. Not able to return the list.

    Kindly help. Below is my python return function

    outlist = 140
    return outlist # it works

    outlist = [140,141]
    return outlist # Amibroker shows error

    I am plotting outlist[0] in both cases.

  3. Does this Python Integration thing Work with AmiBroker 5.6???? Looking for an affirmative reply!!!!!!!!!

  4. how do i copy that iir.py file into the Python bin folder pls? I can’t see a bin folder. Only Python27/ DLLS, DOX, Include, Lib, libs, scripts, tcl and Tools. Python2.7 is an application without a bin folder… thank you

        1. You need to Install the following Python Libraries.

          — numpy-MKL-1.8.2.win-amd64-py2.7.exe
          — statsmodels-0.7.0-4b55fa4.win-amd64-py2.7.exe
          — pandas-0.13.0.win-amd64-py2.7.exe
          — patsy-0.2.1-1_py27.exe
          — python-dateutil-1.5.win-amd64-py2.7.exe
          — scipy-0.14.0.win-amd64-py2.7.exe

          1. Now where do I get it? Would it be available as a single package, or each needs to be downloaded differently?

  5. May I use Anaconda Python Package instead of Python 2.7 for Windows?

    I am sorry. I am not familiar with Windows.

    In the code:
    _reg_clsid_=”{25F32489-9E84-4D9F-8AEB-44DC9B528405}”

    Where do I get this id?

    1. Havent tested with Anaconda Python but if it supports com server then possibly you can do that. I had choosen the id as random however you can use the function

      _reg_clsid_ = pythoncom.CreateGuid()

      so that the system chooses new GUID for you 🙂

  6. Hi Mr Rajendran

    Im getting Com/Handle object is null in the AFL at this line SmValue = MyObj.IIR2(Close,Coef0,Coef1,Coef2);

      1. Hi Rajendran,

        Even after registering python com server, I am still getting the error
        Com/Handle object is null in the AFL at this line SmValue = MyObj.IIR2(Close,Coef0,Coef1,Coef2); Please help.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More