Longbridge OpenAPI SDK

repository·main·Indexed 19 days ago

https://github.com/longbridge/openapi

A multi-language SDK (C, C++, Java, Node.js) providing programmatic access to trading, real-time quotes, portfolio management, and financial market data. It features specialized context types such as QuoteContext, TradeContext, and FundamentalContext, and supports OAuth 2.0 authentication.

Tokens
39.5K
Snippets
128
Records
166
Agent score
65%

What's inside Longbridge OpenAPI

  1. Overview of Longbridge OpenAPI SDK capabilities

    main

    Longbridge OpenAPI provides programmatic interfaces for quote trading, research, and development. It allows developers to build trading tools and strategy analysis tools based on their own investment strategies. The SDK's capabilities are categorized into:

    • Trading: Create, amend, and cancel orders; query today's/past orders and transaction details.
    • Quotes: Access real-time quotes and historical quote data.
    • Portfolio: Real-time queries of account assets, positions, and funds.
    • Real-time subscription: Real-time quotes and push notifications for order status changes.
  2. Understand Longbridge OpenAPI Context Types

    main

    The SDK organizes its functionality into several specialized contexts. Depending on your goal, you will interact with different context types:

    ContextDescription
    QuoteContextReal-time quotes, candlesticks, options, warrants, watchlists, push subscriptions
    TradeContextOrders, positions, account balance, executions, cash flow
    AssetContextAccount statement download
    ContentContextNews, community topics
    FundamentalContextFinancial reports, analyst ratings, dividends, valuation, company overview, shareholders
    MarketContextMarket status, broker holdings, A/H premium, trade statistics, anomaly alerts, index constituents
    CalendarContextFinancial calendar (earnings, dividends, splits, IPOs, macro data, market closures)
    PortfolioContextExchange rates, portfolio P&L analysis
    AlertContextPrice alert management (add/enable/disable/delete)
    DCAContextDollar-cost averaging plan management
    SharelistContextCommunity sharelist management
  3. Understand Longbridge Context Types

    main

    The SDK organizes functionality into specialized Context types. Use the appropriate context based on the data or action you need:

    ContextDescription
    QuoteContextReal-time quotes, candlesticks, options, warrants, watchlists, push subscriptions
    TradeContextOrders, positions, account balance, executions, cash flow
    AssetContextAccount statement download
    ContentContextNews, community topics
    FundamentalContextFinancial reports, analyst ratings, dividends, valuation, company overview, shareholders
    MarketContextMarket status, broker holdings, A/H premium, trade statistics, anomaly alerts, index constituents
    CalendarContextFinancial calendar (earnings, dividends, splits, IPOs, macro data, market closures)
    PortfolioContextExchange rates, portfolio P&L analysis
    AlertContextPrice alert management (add/enable/disable/delete)
    DCAContextDollar-cost averaging plan management
    SharelistContextCommunity sharelist management
  4. Use Asynchronous APIs for Quote and Trade

    main

    The SDK provides AsyncQuoteContext and AsyncTradeContext for asyncio-based workflows.

    Key Differences:

    • Creation: Use .create(config) (this is a synchronous call that returns the context instance).
    • Execution: All I/O methods (like .quote(), .subscribe(), .submit_order()) must be awaited.
    • Async Callbacks: If you want to use an async def function as a callback (e.g., for set_on_quote), you must pass the running event loop to the context creation using loop_=asyncio.get_running_loop().

    Async HTTP Client

    You can also perform raw async requests using await http_cli.request_async(method, path).

    import asyncio
    from longbridge.openapi import Config, AsyncQuoteContext, SubType, PushQuote, OAuthBuilder
    
    def on_quote(symbol: str, event: PushQuote):
        print(symbol, event)
    
    async def main():
        # Async OAuth build
        oauth = await OAuthBuilder("your-client-id").build_async(
            lambda url: print(f"Open this URL to authorize: {url}")
        )
        config = Config.from_oauth(oauth)
        
        # Create async context with the running loop for async callbacks
        ctx = AsyncQuoteContext.create(config, loop_=asyncio.get_running_loop())
        ctx.set_on_quote(on_quote)
        
        # Await operations
        await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
        quotes = await ctx.quote(["700.HK"])
        print(quotes)
        
        await asyncio.sleep(10)
    
    asyncio.run(main())
  5. Understand Longbridge C SDK Context Types

    main

    The SDK organizes functionality into specialized context types. You must create the appropriate context based on the type of data or action you need to perform:

    • QuoteContext: Real-time quotes, candlesticks, options, warrants, watchlists, push subscriptions.
    • TradeContext: Orders, positions, account balance, executions, cash flow.
    • AssetContext: Account statement download.
    • ContentContext: News, community topics.
    • FundamentalContext: Financial reports, analyst ratings, dividends, valuation, company overview, shareholders.
    • MarketContext: Market status, broker holdings, A/H premium, trade statistics, anomaly alerts, index constituents.
    • CalendarContext: Financial calendar (earnings, dividends, splits, IPOs, macro data, market closures).
    • PortfolioContext: Exchange rates, portfolio P&L analysis.
    • AlertContext: Price alert management (add/enable/disable/delete).
    • DCAContext: Dollar-cost averaging plan management.
    • SharelistContext: Community sharelist management.
  6. Use Asynchronous APIs with asyncio

    main

    The SDK provides async versions of the contexts for use with asyncio.

    • Use AsyncQuoteContext.create(config) to instantiate an async quote context.
    • Use AsyncTradeContext.create(config) for async trading.
    • Use AsyncContentContext.create(config) for async content (note: construction is synchronous).
    • Use OAuthBuilder.build_async() for asynchronous OAuth flows.
    • All I/O methods (like .subscribe() or .quote()) must be awaited.
    import asyncio
    from longbridge.openapi import Config, AsyncQuoteContext, SubType, PushQuote, OAuthBuilder
    
    def on_quote(symbol: str, event: PushQuote):
        print(symbol, event)
    
    async def main():
        oauth = await OAuthBuilder("your-client-id").build_async(
            lambda url: print(f"Open this URL to authorize: {url}")
        )
        config = Config.from_oauth(oauth)
        ctx = AsyncQuoteContext.create(config)
        ctx.set_on_quote(on_quote)
        await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
        quotes = await ctx.quote(["700.HK"])
        print(quotes)
        await asyncio.sleep(10)
    
    asyncio.run(main())
  7. Enable Paper Trading mode

    main

    If you are using a simulation account, you must explicitly enable paper trading mode. When enabled, all API calls target the paper trading environment. If you attempt to use a real-money token while paper trading is enabled, the server will return an error.

    Via Environment Variable:

    • macOS / Linux: export LONGBRIDGE_PAPERTRADING=true
    • Windows PowerShell: $env:LONGBRIDGE_PAPERTRADING = "true"

    Programmatically via Config:

    const { Config } = require('longbridge');
    
    const config = Config.fromApikey(
      process.env.LONGBRIDGE_APP_KEY,
      process.env.LONGBRIDGE_APP_SECRET,
      process.env.LONGBRIDGE_ACCESS_TOKEN,
      { enablePapertrading: true },
    );
  8. Authenticate using OAuth 2.0

    main

    The recommended authentication method is OAuth 2.0. Use OAuthBuilder to initiate the authorization flow, which provides a URL for user authorization via a callback function.

    from longbridge.openapi import OAuthBuilder, Config
    
    oauth = OAuthBuilder("your-client-id").build(
        lambda url: print(f"Open this URL to authorize: {url}")
    )
    config = Config.from_oauth(oauth)
  9. Install the Longbridge OpenAPI SDK for Java

    main

    Add the openapi-sdk dependency to your pom.xml file to use the Longbridge Java SDK.

    <dependencies>
        <dependency>
            <groupId>io.github.longbridge</groupId>
            <artifactId>openapi-sdk</artifactId>
            <version>LATEST</version>
        </dependency>
    </dependencies>
  10. Verify credentials with Minimal Verification examples

    main

    If you are unsure if your environment or credentials are correct, run the built-in HTTP client examples for your language. A successful run returns JSON; a 401/403 error indicates credential issues, and a timeout indicates network/proxy issues.

    # Python
    python examples/python/http_client.py
    
    # Node.js
    node examples/nodejs/http_client.js
    
    # Rust
    cargo run --manifest-path examples/rust/Cargo.toml -p http_client
    
    # Java
    cd examples/java/http_client
    mvn -q -DskipTests package
    mvn -q -DskipTests exec:java
  11. Authenticate using OAuth 2.0 (Recommended)

    main

    OAuth 2.0 is the recommended authentication method. It uses Bearer tokens and avoids the need for HMAC signatures.

    Step 1: Register an OAuth Client

    Register your application to obtain a client_id by sending a POST request to the registration endpoint.

    macOS / Linux:

    curl -X POST https://openapi.longbridge.com/oauth2/register \
      -H "Content-Type: application/json" \
      -d '{
        "client_name": "My Application",
        "redirect_uris": ["http://localhost:60355/callback"],
        "grant_types": ["authorization_code", "refresh_token"]
      }'

    Windows (PowerShell):

    Invoke-RestMethod -Method Post -Uri https://openapi.longbridge.com/oauth2/register `
      -ContentType "application/json" `
      -Body '{
        "client_name": "My Application",
        "redirect_uris": ["http://localhost:60355/callback"],
        "grant_types": ["authorization_code", "refresh_token"]
      }'

    Step 2: Build the OAuth Client in Node.js

    Use OAuth.build() to handle the authorization flow. This method automatically checks for a cached token in ~/.longbridge/openapi/tokens/<client_id> (or %USERPROFILE% on Windows) before starting a browser-based flow.

    const { OAuth, Config } = require('longbridge');
    
    async function main() {
      const oauth = await OAuth.build(
        "your-client-id",
        (_, url) => console.log("Open this URL to authorize: " + url)
      );
      const config = Config.fromOAuth(oauth);
      // Use config to create contexts...
    }
    
    main();